我正在开发一个实现运费和诸如此类的基本成本的项目,我需要能够格式化 toString 以便它显示小数点后 2 位的成本。我已经对舍入做了一些研究并实现了 BigDecimal 舍入方法:
public static double round(double unrounded, int precision, int roundingMode) {
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
private double baseCost() {
double cost = (weightInOunces * costPerOunceInDollars);
cost = round(cost, 2, BigDecimal.ROUND_HALF_UP);
return cost;
}
@Override
public String toString() {
return "From: " + sender + "\n" + "To: " + recipient + "\n"
+ carrier + ": " + weightInOunces + "oz" + ", "
+ baseCost();
}
但是,当它打印价值 11.50 美元时,它的价格是 11.5 美元。我知道如何以 System.out.format() 样式格式化小数,但我不确定如何将其应用于 toString。我怎样才能格式化它,以便所有小数都显示为两个值?我也想知道我是否应该使用 BigDecimal,因为课堂上还没有介绍。是否还有其他易于实现的舍入方法也可以格式化双精度值的显示?或者我应该只在 toString 方法中格式化小数?