himeshi
himeshi

Reputation: 485

Java BigDecimal setScale and rounding with half_even

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?

Upvotes: 3

Views: 3054

Answers (1)

Thilo
Thilo

Reputation: 262504

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).

Upvotes: 5

Related Questions