Rounding BigDecimal to *always* have two decimal places

JavaMathBigdecimalRounding

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

value = value.setScale(2, RoundingMode.CEILING)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrad MaceView Question on Stackoverflow
Solution 1 - JavaLouis WassermanView Answer on Stackoverflow