Today, I was trying to revise Java before the term starts. While in the process, I hit a simple addition problem:
System.out.print(124.4 + 18.2); //Outputs 142.6 System.out.print(124.6 + 18.2); //Should output 142.8, right? No... //... // //it outputs 142.7999999999999!
Weird no? After a bit of googling, I found out that this was due to the Java Language Specification, with doubles being converted to strings. (I don't understand the reasoning either)
The solution is to use the BigDecimal class. Wrap each of the double values in a BigDecimal class and invoke the add method in it.
Well, that didn't work properly. In fact, it got worse:
BigDecimal num1 = new BigDecimal(124.6); BigDecimal num2 = new BigDecimal(18.2); System.out.print(num1.add(num2)); //Outputs 142.7999999999999936051153781590983271598815917968
The problem is still there!
Turns out that the solution was very simple:
BigDecimal num1 = new BigDecimal("124.6"); BigDecimal num2 = new BigDecimal("18.2"); System.out.print(num1.add(num2)); //Outputs 142.8 - FINALLY!!
So ladies and gentlemen, remember to use the BigDecimal for your decimal calculations AND to pass the value as a String! Or you will see funny long numbers appearing mysteriously!
It's back to school next week! Looking forward to meeting new faces!
1 comment:
Double values are definitely NOT converted to strings for computation. The reason for the inaccuracy is the limited number of bits used by the double datatype. Double is represented using 64bits. Given that there are infinitely many real numbers, we can only approximate it using 64bits, hence there will be some values that cannot be represented precisely. For the gory details, refer to http://citeseer.ist.psu.edu/goldberg91what.html
Post a Comment