截断double或将额外的0添加到小数 - Java

时间:2013-02-14 21:59:16

标签: java formatting double truncate

这可能是重复的,但我找不到任何符合我的代码的答案。

我试图在Java中截断我的结果(用于计算费用)。然后我尝试将结果写入文本文件,但它没有显示它应该。这就是我得到的以及我希望它返回的内容:

  1. 费用结果为8.4,应返回8.40
  2. 费用结果为8.0,应返回8.00
  3. 等等......有什么建议吗?

    这是我的方法的全部代码:

    public Double calculateFee(Parcel pcl) {    
        // Get type of parcel (E, S or X)
        String typeOfParcel = pcl.getParcelID().substring(0,1);
        // Formula for calculating fee
        Double fee = (double) 1 + Math.floor(pcl.getVolume()/28000) + (pcl.getDays()-1);
    
        // apply a discount to parcels of type "S"
        if (typeOfParcel.equalsIgnoreCase("S")) {
            fee = fee * 0.9;
        }
    
        // apply a discount to parcels of type "X"
        else if (typeOfParcel.equalsIgnoreCase("X")) {
            fee = fee * 0.8; 
        } 
    
        // This is what I tried:
        // Tried also using #.##, but no result
        DecimalFormat decim = new DecimalFormat("0.00");
        fee = Double.parseDouble(decim.format(fee));
    
        return fee;     
    } 
    

2 个答案:

答案 0 :(得分:2)

一种方法是使用String.format()。

  Double fee = 8.0;
  String formattedDouble = String.format("%.2f", fee );

请注意,Double不保存其值的格式化表示。

有关格式字符串的其他详细信息,请here

答案 1 :(得分:1)

这里的问题不在于您将其格式化错误。您正在使用以下方式格式化双精度:

decim.format(fee);

然后,您将此字符串解析为Double,从而丢失格式:

Double.parseDouble(...

只返回一个String而不是Double,不要使用Double.parseDouble。