【发布时间】:2024-01-22 02:14:01
【问题描述】:
这可能是重复的,但我找不到任何适用于我的代码的答案。
我正在尝试为 Java 中的一种方法(用于计算费用)截断结果。然后我尝试将结果写入文本文件,但它并没有像应有的那样显示。这是我得到的,也是我希望它返回的:
- 费用结果是8.4,应该返回8.40
- 费用结果是8.0,应该返回8.00
等等……有什么建议吗?
这是我的方法的完整代码:
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;
}
【问题讨论】:
-
你为什么要再次解析格式化的双精度数以返回双精度数?只需返回
DecimalFormat.parse返回的字符串形式即可。 -
@RohitJain 是正确的:这是无意义的代码
-
为什么你返回
double作为格式化代码的结果,而不是String? -
我不知道格式不能应用于 Double 类型。对不起,初学者的错误。
标签: java formatting double truncate