Floating point precision error in Java
I want to know what is the best way to fix precision errors in Java As shown in the following example, there is a precision error:
class FloatTest
{
public static void main(String[] args)
{
Float number1 = 1.89f;
for(int i = 11; i < 800; i*=2)
{
System.out.println("loop value: " + i);
System.out.println(i*number1);
System.out.println("");
}
}
}
The results displayed are:
In addition, if anyone can explain why it only starts at 11 and doubles its value every time I think all other values (or at least many) show the correct results
Problems like this give me a headache. I usually use a number formatter or put them in a string
Editor: as people say, I can use a double, but after trying, it seems that 1.89 as double 792 still outputs an error (the output is 1496.87999999999)
I think I will try other solutions, such as BigDecimal
Solution
If you really care about accuracy, you should use BigDecimal
http://download.oracle.com/javase/1 ,5.0/docs/api/java/math/BigDecimal. html
