【问题标题】:Decimal Formatting is not working十进制格式不起作用
【发布时间】:2013-11-16 19:07:58
【问题描述】:

我希望能够确保一个数字只有两位小数。

输入的 E.G 区域 = 256.12345,因此区域将为 256.12。

这就是我所拥有的:

DecimalFormat df = new DecimalFormat( "#,###,###,##0.00" );
double area = new Double(area.format(area)).doubleValue();
area = (double)(r*r);

【问题讨论】:

  • 你在哪里使用df

标签: java decimal number-formatting


【解决方案1】:

您实际上并未使用实例df

更改您的代码以使用它,而不是在 area 上调用方法(这不起作用,因为原语没有方法):

double area = new Double(df.format(area)).doubleValue();

但是,精度的形式更多是出于打印目的而不是存储目的(Double 会将其存储在双精度的 IEEE 浮点标准中,这可能会导致浮点值不精确)。

要解决这个问题,请改用 BigDecimal,精度为 2:

BigDecimal decimal = new BigDecimal(area);
decimal.setScale(2);
System.out.println(decimal); // will print area to two decimal places

【讨论】:

    【解决方案2】:

    这就是你的做法。

    //formatting numbers upto 2 decimal places in Java
            DecimalFormat df = new DecimalFormat("#,###,##0.00");
            System.out.println(df.format(364565.14));
            System.out.println(df.format(364565.1454));
    
            //formatting numbers upto 3 decimal places in Java
            df = new DecimalFormat("#,###,##0.000");
            System.out.println(df.format(364565.14));
            System.out.println(df.format(364565.1454));
        }
    
    }
    
    Output:
    364,565.14
    364,565.15
    364,565.140
    364,565.145
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多