Java BigDecimal: Round to the nearest whole value

后端 未结 6 755
滥情空心
滥情空心 2020-11-27 16:41

I need the following results

100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

.round() or

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 17:32

    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.HALF_UP);
    System.out.println(value + " -> " + scaled);
    

    Using round() is a bit more involved as it requires you to specify the number of digits to be retained. In your examples this would be 3, but this is not valid for all values:

    BigDecimal rounded = value.round(new MathContext(3, RoundingMode.HALF_UP));
    System.out.println(value + " -> " + rounded);
    

    (Note that BigDecimal objects are immutable; both setScale and round will return a new object.)

提交回复
热议问题