【问题标题】:How to format a float number in Jason to show only two decimals?如何在 Jason 中格式化浮点数以仅显示两位小数?
【发布时间】:2018-02-12 23:30:30
【问题描述】:

如何在 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

【问题讨论】:

    标签: artificial-intelligence agent multi-agent


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多