我正在开发一个项目,该项目实现运费等基本成本,我需要能够格式化 toString 以便它显示带有两位小数的成本。我已经对舍入进行了一些研究并实现了 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,因为类(class)中尚未介绍这一点。是否有其他易于实现的舍入方法也可以格式化 double 值的显示?或者我应该在 toString 方法中格式化小数?
最佳答案
您可以在toString
中应用DecimalFormat
。关于BigDecimal
的适用性,如果您正在处理金钱,并且需要精度,请使用BigDecimal。
@Override
public String toString() {
DecimalFormat format = new DecimalFormat("#.00");
return "From: " + sender + ... + format.format(baseCost());
}
如果您从 round
方法返回 BigDecimal
而不是 double
,则 float 精度不会丢失。
关于java - 在 toString 方法中格式化小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14678523/