This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes how to sum floats Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "how to sum floats" Watch "how to sum floats" New topic

how to sum floats

Tapio Niemela
Ranch Hand

Joined: Jan 06, 2006
Posts: 77
I'm bit puzzled..I should compare one double value with a sum of other double values

I've read it is because of rounding inaccuracy. To my understanding this is because of how numbers are stored (as binary values)

However, is there any way to successfully compare 0.2+0.2+0.2 to 0.6? Or similar. Numbers can be anything, not just 0.2..

With currency I could convert 1.34$ to 134 pennies and use that, but in my case that's not possible, as I don't know the actual numbers, so I can't just multiply the "source" with 100..

Or do I have to accept inaccuracy and threat two counted decimals equal if their difference is low enough..(with the example 0.6000000000000001-0.6=000000000000001--> numbers can be considered "equal")?

thanks in advance
Paul Clapham

Joined: Oct 14, 2005
Posts: 18541

Well, you should use BigDecimal if you want to use exact decimal numbers instead of binary approximations of them. But you should also read the documentation for the BigDecimal constructor you used. Not just the one-line summary, the full documentation. Really. It answers the question you are asking here.
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
Try this:
This is because literals 0.2 or 0.6 casted to double cannot be represented as 'exactly' the same numbers using floating point binary representation,
but if you use strings in call to BigDecimal constructor, numbers are not casted to double, but directly to internal BigDecimal representation.
This is described here:

You will see this effect if you run this:
Result is:
I agree. Here's the link:
subject: how to sum floats
Similar Threads
Dice probability program, using nested loops.
Need Helping Sorting Array of Doubles But Need To Know Index Position
Double is doing something weird!
Percision problems with Double and Float numbers
converting a double value