I'm trying to round BigDecimal values up, to two decimal places.
I'm using
BigDecimal rounded = value.round(new MathContext(2, RoundingMode.CEILING));
logger.trace("rounded {} to {}", value, rounded);
but it doesn't do what I want consistently:
rounded 0.819 to 0.82
rounded 1.092 to 1.1
rounded 1.365 to 1.4 // should be 1.37
rounded 2.730 to 2.8 // should be 2.74
rounded 0.819 to 0.82
I don't care about significant digits, I just want two decimal places. How do I do this with BigDecimal? Or is there another class/library better suited to this?
Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point.
You can use setScale() to reduce the number of fractional digits to zero. Assuming value holds the value to be rounded: BigDecimal scaled = value. setScale(0, RoundingMode.
The default is HALF_UP, meaning that the rounding mode is to round toward the nearest neighbor unless both neighbors are equidistant, (and in this case, round toward the even neighbor).
Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.
value = value.setScale(2, RoundingMode.CEILING)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With