This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Floating point variables aren't very good at storing exact values. Remember that the number is stored internally in binary, and 2095475.03 won't be represented exactly in binary.
So you've got two options.
- If you need the calculations to be exact, then look at using the BigDecimal class to represent numbers and do calculations.
- If you don't care about these tiny inaccuracies, but all you care about is getting sensible output, do the calculations as you are, and try the DecimalFormat class to produce output to the accuracy you want.
That is how floating point calculations work. It basically is because not every number can be stored in a double so it will take the closed value. If you want it to have a certain format then you can use NumberFormat.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Thanks what I was trying to do was importing a file.
The header had a total which was giving the value 2098700.03
which will be compared against the total of the relevant filed(of Numeric(5,2)) which is a double in the body
which can be from upto a total of 50000 rows.
This total also represented as a double was returning as 2098700.0300000003 and hence it was throwing an error beacuse the values didn't match.
I will try using BigDecimal
Comparing floating point numbers for equality is ALWAYS risky in any computer language. if you have to do so, you generally figure out some delta that the difference should be less than...i.e.:
And even this is dangerous if the magnitude of your numbers can vary.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Jun 17, 2010
I have overcome the issue firt mentioned in my post using BigDecimal.
Now I have a different one.
Bigdecimal one = 2948.0
Bigdecimal one = 2948 (this is being returned from a jdbc query of Double value new BigDecimal(resultRow.getFee().toString());)
Again failing on comparison, anway to impose the decimal ?