Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BigDecimal setScale and rounding with half_even

Tags:

java

I am using the following code with the java BigDecimal setScale method with half_even rounding mode and am getting the following results.

new BigDecimal(1.115).setScale(2, RoundingMode.HALF_EVEN).toPlainString()

Result: 1.11

Expected: 1.12

Since the closest even digit to the left to 5 should be 2 the result I would expect is 1.12. But the result is 1.11. And again,

new BigDecimal(1.145).setScale(2, RoundingMode.HALF_EVEN).toPlainString()

Result: 1.15

Expected: 1.14

Because the even digit to the left of 5 is 4 I would expect the result to be 1.14. Any explanation for this?

like image 943
Himeshi Avatar asked Jul 22 '26 12:07

Himeshi


1 Answers

This is caused by floating point imprecisions (in your double input value).

System.out.println(new BigDecimal(1.115));

1.1149999999999999911182158029987476766109466552734375

Use the String constructor instead.

BigDecimal.valueOf("1.115")

Once the number is a BigDecimal, no precision is lost and rounding works properly. But you have to make sure the number gets into the BigDecimal intact (and has not already lost precision before that by forcing it through a floating point type).

like image 108
Thilo Avatar answered Jul 25 '26 04:07

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!