Java BigDecimal: Round to the nearest whole value

后端 未结 6 751
滥情空心
滥情空心 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条回答
  •  日久生厌
    2020-11-27 17:18

    Here's an awfully complicated solution, but it works:

    public static BigDecimal roundBigDecimal(final BigDecimal input){
        return input.round(
            new MathContext(
                input.toBigInteger().toString().length(),
                RoundingMode.HALF_UP
            )
        );
    }
    

    Test Code:

    List bigDecimals =
        Arrays.asList(new BigDecimal("100.12"),
            new BigDecimal("100.44"),
            new BigDecimal("100.50"),
            new BigDecimal("100.75"));
    for(final BigDecimal bd : bigDecimals){
        System.out.println(roundBigDecimal(bd).toPlainString());
    }
    

    Output:

    100
    100
    101
    101

提交回复
热议问题