Reputation: 1306
I have been working on a tolerance calculation code written in Double
, having precisions and rounding issues I decided to move on to BigDecimal
considering it's more precise and less likely to encounter rounding issue.
In a calculation, piece of code uses Math.floor()
and Math.Ceil
when dividing values.
Strange observation that ROUNDING_MODE.floor
and ceil
does not actually apply when using BigDecimal
, here's the minimal re-producable example.
Double doubleFloor = Math.floor(5.5/1.0);
Double doubleCeil = Math.ceil(5.5/1.0);
System.out.println(doubleFloor);
System.out.println(doubleCeil);
BigDecimal bigDecimalFloor = BigDecimal.valueOf(5.5).divide(BigDecimal.ONE,1,RoundingMode.FLOOR);
BigDecimal bigDecimalCeil = BigDecimal.valueOf(5.5).divide(BigDecimal.ONE,1,RoundingMode.CEILING);
System.out.println(bigDecimalFloor);
System.out.println(bigDecimalCeil);
I'd expect to print identical value for such small division however I get following, floor and ceil does not seem to be calculated as expected.
5.0
6.0
5.5
5.5
What is it that I am missing. ?
Thank you in Advance
Upvotes: 0
Views: 418
Reputation: 140299
To quote the Javadoc
If rounding must be performed to generate a result with the specified scale, the specified rounding mode is applied.
5.5
doesn't need to be rounded when the scale is 1, so the rounding mode isn't applied.
It would work like Math.floor
and Math.ceil
if the scale were 0:
BigDecimal bigDecimalFloor = BigDecimal.valueOf(5.5).divide(BigDecimal.ONE,0,RoundingMode.FLOOR);
BigDecimal bigDecimalCeil = BigDecimal.valueOf(5.5).divide(BigDecimal.ONE,0,RoundingMode.CEILING);
System.out.println(bigDecimalFloor);
System.out.println(bigDecimalCeil);
Output
5
6
Upvotes: 5