How to format a float number in Jason to show only two decimals?

259 views Asked by At

How to format a number as a currency with two decimals in Jason?

The code bellow illustrates the case:

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

The output is, I'd like to make the output more readable. Notice that float point numbers have many algharisms.:

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

There are 1 answers

0
Cleber Jorge Amaral On

In fact there is no default internal action in Jason to format it as you want. Howeven, you can create your own Internal Action doing like this:

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

In your agent, you can call this action by:

package_name.formatCurrency(10.5555,Price);