Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# how to sum floats

Tapio Niemela
Ranch Hand
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")?

Paul Clapham
Sheriff
Posts: 22480
43
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
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: