Problems with the result of a sum between double-type numbers

Asked

Viewed 704 times

0

I want to make the following calculation:

615.6555 + 566

I expected this result:

1181.6555

However, this is me returning this:

1181.6554999999998

How do I solve this problem?

2 answers

2


For mathematical calculations always use Bigdecimal. Bigdecimal is a class that works with arbitrary precision floating point numbers, which choose how much precision you want to use. But there’s an interesting catch here, in case you use Bigdecimal that way:

BigDecimal b1 = new BigDecimal(615.6555);
BigDecimal b2 = new BigDecimal(566);

System.out.println(b1.add(b2));

You will receive the same unexpected result. The documentation itself provides for this possibility: "The results of this constructor can be unpredictable". You have two solutions to handle this problem, according to the documentation itself, the first would be to use String:

BigDecimal b1 = new BigDecimal(Double.toString(615.6555));

And the second, if you want to keep the double instead of converting it, use the static method valueOf:

BigDecimal b1 = BigDecimal.valueOf(615.6555);

1

For accounts with large number of decimals it may be interesting to use the class

java.math.BigDecimal

So the account would be this way:

BigDecimal valor1 = new BigDecimal("615.6555");
BigDecimal valor2 = new BigDecimal("566");
BigDecimal soma = valor1.add(valor2);
System.out.println(soma); // Imprime 1181.6555

Also, with this class you can easily control the accuracy of tithe values with the method setScale, and of course, in addition to other arithmetic operations. See a practical and didactic example:

Java.math.Bigdecimal.setScale() Method

Browser other questions tagged

You are not signed in. Login or sign up in order to post.