Sum of two floats with 2 decimal places resulting in 4 decimal places in JAVA

I am having a problem in JAVA where I want to store calculation results with only 2 decimal places in SQL Server. For this at the end of my calculations I perform:

Math.round(valor * 100.0f) / 100.0f;

To get the value with two decimal places. After entering the values in the bank I am querying them and really are only stored with 2 decimal places.

When I perform the request for SELECT they are coming with 2 decimal places as well.

But the strange happens when I try add two of these values, the result of this sum gives a number with 4 decimal places, follows debug image:

Unexpected result

What could be happening? Is this way of rounding right?

--

Also when requesting INSERT (just to make sure that the value will be inserted with 2 decimal places):

INSERT INTO tableX (valor) values (ROUND(?,2))

But continues to result in a number of 4 decimal places after the sum.

Author: Lucas Penido, 2019-11-06

1 answers

That's right, that's because of conversions, and it happens not only in Java, but in many other languages, you're not doing wrong.

If you want to format, do calculations or in your case, from what I think Is Beautiful Money, use the format BigDecimal.

Here is an English thread about this: https://stackoverflow.com/questions/9906169/weird-java-behavior-how-come-adding-doubles-with-exactly-two-decimal-places-res

 0
Author: leofalmeida, 2019-11-06 17:50:30