Possible Duplicate:
Retain precision with Doubles in java
Moving decimal places over in a double
For example, something as simple as this:
public class WrongAnswer {
public static void main(String[] args) {
System.out.println(100*1.1);
}
}
prints 110.00000000000001 instead of 110. Using other numbers instead of 100*1.1 also give a lot of digits with some random digit at the end that isn't right..
Any ideas?
Floating point notations have limited degrees of accuracy. Here's a guide: http://floating-point-gui.de/
Most floating point calculations involve rounding errors. In your case, there are two rounding errors: converting (decimal) 1.1 to floating point (there's no exact representation for 1.1 in IEEE 754 floating point--which is what Java uses) and then multiplying by 100. See the excellent article What Every Computer Scientist Should Know About Floating-Point Arithmetic for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With