0

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 ?

Stephan
  • 41,764
  • 65
  • 238
  • 329
  • `System.out.println(exprEvaluator.evalf("round(100*17347*0.047)*0.01"));` gives result highly likely `815.3100000000001`, the result has nothing to with it being `double` or the assignment. – Soner from The Ottoman Empire Aug 07 '18 at 14:15

1 Answers1

1

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.