I'm using Symja.
On http://matheclipse.org/, when I run the following formula:
round(100*17347*0.047)*0.01
I get: 815.31
When running the following Java code
ExprEvaluator exprEvaluator = new ExprEvaluator(false,100);
double d = exprEvaluator.evalf("round(100*17347*0.047)*0.01");
System.out.println(d);
I get: 815.3100000000001
What am I missing ?
There is no wrong with the code. If you wish to get only 2 precision of the number, I mean to print, use printf()
in lieu of println()
ExprEvaluator exprEvaluator = new ExprEvaluator(false,100);
double d = exprEvaluator.evalf("round(100*17347*0.047)*0.01");
System.out.printf("%.2f\n", d);
Or, if you want its numerical rounded value, you can use Java's DecimalFormat
double d = 815.3100000000001;
System.out.println(d);
DecimalFormat newFormat = new DecimalFormat("#.##");
double twoDecimal = Double.valueOf(newFormat.format(d));
System.out.println(twoDecimal);
Even more, if you are uncomfortable with its behaviour, override the evalf
method and use Math.round(...)
within it. It results in your wish without needing additional Java methods. Moreover, you should glance at implementation of evalf
.