BigDecimal舍入模式

时间:2019-01-06 07:39:21

标签: java rounding bigdecimal

我们正在将一些sybase代码替换为Java,并对Rounding BigDecimal匹配sybase返回的内容存在疑问

11.4443999999999999062083588796667754650115966796875-应该返回11.44

35.9549999999999982946974341757595539093017578125-应该返回35.96

我尝试将比例设置为2的所有不同的舍入选项,但是对这两种都不起作用。最好的选择是什么?

2 个答案:

答案 0 :(得分:0)

此解决方案效率不高,但可以完成工作。

源代码

import java.math.BigDecimal;

public class BigDecimalRound {
    public static void main(String[] args) {
        BigDecimal bd;
        float f;

        bd = new BigDecimal(11.4443999999999999062083588796667754650115966796875);
        f = roundBigDecimal(bd, 2);
        System.out.println("bd: " + bd + ", f: " + f);

        bd = new BigDecimal(35.9549999999999982946974341757595539093017578125);
        f = roundBigDecimal(bd, 2);
        System.out.println("bd: " + bd + ", f: " + f);
    }

    public static float roundBigDecimal(BigDecimal bd, int precision) {
        int i = (int) Math.pow(10, precision);
        return (float) Math.round(bd.floatValue() * i) / i;
    }
}

输出

bd: 11.4443999999999999062083588796667754650115966796875, f: 11.44
bd: 35.9549999999999982946974341757595539093017578125, f: 35.96

答案 1 :(得分:0)

您必须采取两步方法。首先使用RoundingMode.HALF_UP将比例缩放为3,然后缩放为2:

BigDecimal value1 = new BigDecimal("11.4443999999999999062083588796667754650115966796875");      
BigDecimal value2 = new BigDecimal("35.9549999999999982946974341757595539093017578125"); 

BigDecimal rounded1 = value1.setScale(3, RoundingMode.HALF_UP); // 11.444
rounded1 = rounded1.setScale(2, RoundingMode.HALF_UP);          // 11.44

BigDecimal rounded2 = value2.setScale(3, RoundingMode.HALF_UP); // 35.955
rounded2 = rounded2.setScale(2, RoundingMode.HALF_UP);          // 35.96