Java BigDecimal: Round to the nearest whole value

后端 未结 6 746
滥情空心
滥情空心 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:34

    I don't think you can round it like that in a single command. Try

        ArrayList list = new ArrayList();
        list.add(new BigDecimal("100.12"));
        list.add(new BigDecimal("100.44"));
        list.add(new BigDecimal("100.50"));
        list.add(new BigDecimal("100.75"));
    
        for (BigDecimal bd : list){
            System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));
        }
    
    Output:
    100.12 -> 100.00
    100.44 -> 100.00
    100.50 -> 101.00
    100.75 -> 101.00
    

    I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.

提交回复
热议问题