252

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?

Brad Mace
  • 27,194
  • 17
  • 102
  • 148

1 Answers1

463
value = value.setScale(2, RoundingMode.CEILING)
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • 19
    That does indeed work how I want. Is the difference simply that `round()` works with significant digits while `setScale` works with a fixed number of decimal places or is there more to it? – Brad Mace Mar 26 '13 at 17:21
  • 58
    Use RoundingMode.HALF_UP to do "typcal rounding". That is 1.111 gives 1.11 [CEILING gives 1.12] – Grzegorz Dev Oct 14 '16 at 05:30
  • 7
    Thanks for `RoundingMode.HALF_UP`. As per documentation it is the rounding method commonly taught in schools - what I needed. – k_rollo Jul 16 '17 at 05:40
  • 1
    Take care if your values can be negative as in an accounting application. You may need to use RoundingMode.UP instead of CEILING – Dale Mar 09 '18 at 21:17
  • 2
    Why does `setScale(...)` work? see [BigDecimal setScale and round](https://stackoverflow.com/questions/3843440/bigdecimal-setscale-and-round). – Jason Law Nov 26 '19 at 09:53
  • I want 1.00 divided by 3 BigDecimal to get 0.33. But then i am getting 0.30. – Saiprashanth May 31 '23 at 09:35