0

如何在 Jason 中将数字格式化为具有两位小数的货币?

下面的代码说明了这种情况:

products([["Banana",1], ["Apple",2], ["Pinapple",2.5]]).
margin(2).

!printPrices.

+!printPrices: products(List) & margin(Z)<-
 .length(List,LLenght);
 -+listSize(0);
 while(listSize(Sz) & Sz < LLenght)
 {        
  .random(Y);
  .nth(Sz,List,Item);
  .nth(0,Item,Name);
  .nth(1,Item,Price);
  .print("Product(",Sz,"): ",Name," Price $",Y*Z+Price);
  -+listSize(Sz+1);
 }.

输出是,我想让输出更具可读性。请注意,浮点数有许多算法:

[sampleagent] Product(0): Banana Price $1.3689469979841409 
[sampleagent] Product(1): Apple Price $2.0475157980624523
[sampleagent] Product(2): Pinapple Price $3.4849443740416803
4

1 回答 1

0

事实上,Jason 中没有默认的内部操作来根据需要对其进行格式化。但是,您可以像这样创建自己的内部操作:

import jason.asSemantics.*;
import jason.asSyntax.*;

public class formatCurrency extends DefaultInternalAction {

    private static final long serialVersionUID = 1L;

    @Override
    public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {

        StringTerm result = new StringTermImpl(String.format("%.2f", Float.valueOf(args[0].toString())));
        un.unifies(result, args[1]); 

        return true;
    }
}

在您的代理中,您可以通过以下方式调用此操作:

package_name.formatCurrency(10.5555,Price);
于 2017-12-13T12:42:13.857 回答