posted 9 years ago

Floating point numbers have finite precision, and there are some (many) numbers that can't be represented exactly. Many multiples of 0.1 are among these.

Note that the value of 2.05*1000000 is

System.out.format("%.0f\n", 2.05*1000000 );

prints "2050000".

Note that the value of 2.05*1000000 is

*not*2049999; it's 2049999.9999999998, which is considerably closer to the exact answer. All you need to do is be careful about how you display the results of floating-point calculations. Instead of just System.out.println(number) use System.out.format() or java.text.DecimalFormat, which will let you round more intelligently. For example,System.out.format("%.0f\n", 2.05*1000000 );

prints "2050000".

Consider Paul's rocket mass heater. |