Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting wrong result for evaluation of 100 * 2.55 values

Tags:

java

I am getting wrong result using below method.

public double evaluate(final double leftOperand, final double rightOperand) {
        Double rtnValue = new Double(leftOperand * rightOperand);
        return rtnValue.doubleValue();
    }

Enter Parameter value are: leftOperand= 100 and rightOperand=2.55

I am getting Wrong answer: 254.99999999999997

The correct answer is a 255.0

like image 582
bNd Avatar asked Jul 31 '12 10:07

bNd


2 Answers

Use BigDecimal

BigDecimal bd = new BigDecimal("100");
BigDecimal ans = bd.multiple(new BigDecimal("2.55"));
System.out.println(ans);

See Also

  • Working IDE One demo

  • Retain precision with double in Java

like image 84
jmj Avatar answered Sep 30 '22 17:09

jmj


This is due to floating point precision problem. It is impossible to represent every rational number within 64 bits. The numbers are stored within the IEEE 754 format.

If you are creating a game, this is more than good enough, even float will do. But if you are doing some finance, it should be correct. Then you can use java.math.BigDecimal. It is much slower than double but it is correct. And it takes much more memory, since you have an exact value in memory. Here is a nice tutorial on how to use BigDecimal.

like image 25
Martijn Courteaux Avatar answered Sep 30 '22 19:09

Martijn Courteaux