在toString方法中格式化小数?

时间:2013-02-03 23:20:10

标签: java rounding

我正在开发一个实现运费基本成本的项目,以及我需要能够格式化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,因为它尚未在课堂上引入。还有其他易于实现的舍入方法,也会格式化double值的显示吗?或者我应该在toString方法中格式化小数?

2 个答案:

答案 0 :(得分:1)

您可以在DecimalFormat中应用toString。关于BigDecimal的适当性,如果您正在处理金钱,那么需要精确度,请使用BigDecimal。

@Override
public String toString() {

   DecimalFormat format = new DecimalFormat("#.00");

   return "From: " + sender + ... + format.format(baseCost());
}

如果从BigDecimal方法返回double而不是round,则浮动精度不会丢失。

答案 1 :(得分:0)

使用DecimalFormatdouble打印为String,并带有两位小数。

@Override
public String toString() {
    DecimalFormat df = new DecimalFormat("#.00");
    return "From: " + sender + "\n" + "To: " + recipient + "\n"
            + carrier + ": " + weightInOunces + "oz" + ", "
            + df.format(baseCost());
}