如何在Jason中格式化浮点数以仅显示两位小数?

时间:2017-09-04 17:40:19

标签: artificial-intelligence agent multi-agent

如何在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);
 }.

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

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

1 个答案:

答案 0 :(得分:1)

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

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);