【问题标题】:Strange BigDecimal value using DecimalFormat使用 DecimalFormat 的奇怪 BigDecimal 值
【发布时间】:2015-02-24 15:35:05
【问题描述】:

我正在尝试使用 DecimalFormat 将一些字符串值转换为数字。我试图以更好的方式向您解释我的问题:

我有以下方法:

private BigDecimal loadBigDecimal(String value){

    BigDecimal bigDecimalToReturn = null;
    DecimalFormat df = new DecimalFormat("##.###");
    bigDecimalToReturn = new BigDecimal(df.parse(value).doubleValue());
    return bigDecimalToReturn;
}

现在如果我尝试运行该方法:

BigDeciaml dec = myObject.loadBigDecimal("120,11");

dec 的值为120.1099999999999994315658113919198513031005859375。 为什么 decimalFormat 会改变我的值的比例?

【问题讨论】:

    标签: java bigdecimal decimalformat


    【解决方案1】:

    您正在转换为双精度和反向。这是不必要的,并且会引入舍入错误。您应该使用以下代码:

    private BigDecimal loadBigDecimal(String value) throws ParseException {
        DecimalFormat df = new DecimalFormat("##.###");
        df.setParseBigDecimal(true);
        return (BigDecimal) df.parse(value);
    }
    

    【讨论】:

      【解决方案2】:

      双打只是近似值。这对于双倍来说是正确的。如果你想要一个特定的比例,你需要在 BigDecimal 构造函数中告诉它。

      【讨论】:

        【解决方案3】:

        这是因为df.parse(value).doubleValue() 调用。此时,该值被转换为双精度值。

        double 表示加或减 2 的幂的和(有正负指数)。

        120 可以写成 64+32+16+8。

        但不能将 0.11 写成 2 的有限幂和。

        所以有一个近似值。

        0.1099999999999994315658113919198513031005859375

        这是2的幂。

        它看起来像 constructor with a string for parameter 的 BigDecimal。也许你可以使用它。

        BigDecimal dec = new BigDecimal("120,11");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-12
          • 1970-01-01
          相关资源
          最近更新 更多