I have a very simple piece of code below which I think gives the wrong result from a user’s perspective.
package com.test.sample;
public class Test {
public static void main(String[] args) {
float c,d;
c = (float) 12.47;
d = (float) 12.44;
d = c - d;
System.out.println("Hello the calculated value of a=" + d);
}
}
The output is
Hello the calculated value of a=0.030000687
But I want a=0.030000000 which is the perfect value.
Floating point arithmetic, what developers should know.
The JVM implements the IEEE-754 1985 floating point standard and it has its accuracy problem (since floating point numbers cannot precisely represent all real numbers).
If you seek accuracy, use
java.math.BigDecimalobject instead.Update: This is how I took your example and used
BigDecimalto achieve your expected result: