Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the correct behavior for rounding with BigDecimals?

I am trying to round BigDecimals like this: 5.46597 -> 5.46, I thought the code below does this for me, but not.

I tried it with BigDecimal.round and BigDecimal.setScale.

BigDecimal bD = new BigDecimal(5.46597); // whole number: 5.4659700000000004393996277940459549427032470703125 
bD.setScale(2, RoundingMode.HALF_DOWN); // 5.47
bD.round(new MathContext(3, RoundingMode.HALF_DOWN)); // 5.47

Isn't this should be 5.46, or what do I misunderstood?

like image 247
Skezo Avatar asked Dec 13 '25 08:12

Skezo


2 Answers

HALF_DOWN only rounds down when the actual value is exactly half-way between the two possible rounded values. I.e. 5.46500 -> 5.46. On the other hand 5.4650000001 -> 5.47 because that's nearer to 5.47 than 5.46.

Perhaps what you're looking for is RoundingMode.DOWN, which always rounds down.

like image 140
Klitos Kyriacou Avatar answered Dec 15 '25 20:12

Klitos Kyriacou


Rounding with BigDecimal using ROUND_HALF_DOWN is defined in JavaDoc as "ROUND_HALF_DOWN - Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down." Documentation ROUND_HALF_DOWN Documentation RoundingMode.HALF_DOWN

For BigDecimal.valueOf("5.46597").setScale(2, BigDecimal.ROUND_HALF_DOWN) the nearest neighbors are 5.46 and 5.47 with distances of 0.00597 and 0.00403. So the distance to 5.47 is smaller (nearer) than to 5.46 which results in rounding to 5.47.

like image 41
SirFartALot Avatar answered Dec 15 '25 21:12

SirFartALot



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!