The simple solution is to use ints representing the numbers times 100 (can be useful when dealing with adding / subtracting simple money values; the ints then represent the cents), or more intuitively use BigDecimal.
Fernando Dominguez wrote:Hello,
I'm trying to add to Doble numbers with 2 decimal places, 12,25 + 23, 46 = 35, 71
I get most of the time.
But some times, for example, 12,10 + 20,15 gets 32,24999999999999999999996
Thanks in advance
I'm a student engineer, no java expert at all but I can tell you a bit about numerical math:
A simple sum like 12,10 + 20,15 that gets 32,24999999999999999999996 is impossible in my opinion.
Rounding errors like these can come however from for example:
Endless numbers like pi and 0.99999999...., they will only be saved to about 16 numbers exact (I think) and therefore have some rounding errors.
Doing multiple operations with such numbers can result increase these rounding errors.
Doing operations with really small numbers is also verry unstable.
It's not java's fault, it's just the way computers work with numbers. You have to search for a more "Numerical stable" algorithm.
Using the BigDecimal class for your operations can also solve the problem because you will then save your numbers to more places exact.
I hope this very short intro to numerical math answered a bit of your question.
IEEE 754 floating point numbers are stored as binary fractions. Some numbers simply cannot be represented with a finite number of digits by a binary fraction, just like some numbers like 1/3 cannot be represented by a finite number of digits as a decimal fraction.
If you need arbitrary precision, use BigDecimal instead of float or double.
And you are most definitely right that this is not Java's fault. The same will happen in almost every programming language, since the problem is caused by the underlying system.