如何在小数点后最多打印2位数?

时间:2016-03-16 20:21:01

标签: java

我的打印格式有一个小问题。 我想在小数点后打印2位数字 不是整数(例如55.53467 - > 55.53)和小数点后的1位数 如果数字是整数或在小数点后面有一个圆数(对于 例2.00 - > 2.0或5.10 - > 5.1)。

我所拥有的代码是:

public String toString() {

    return String.format("%+.2f%+.2fX%+.2fX^2%+.2fX^3%+.2fx^4", this.A0.getCoefficient()
                                                              , this.A1.getCoefficient()
                                                              , this.A2.getCoefficient()
                                                              , this.A3.getCoefficient()
                                                              , this.A4.getCoefficient());
}

但它总是打印2位数。 非常感谢

2 个答案:

答案 0 :(得分:0)

在这种情况下,我将使用DecimalFormat“0.0#”格式化浮点数(#表示:仅在不为零时设置)到String-Vars并将结果传递给函数String.format。

答案 1 :(得分:0)

您可能希望利用DecimalFormat,例如:

public static String format(double num, double places) {
    String format = "#.";
    for(int i=0; i<places; i++) format += "0";
    DecimalFormat df = new DecimalFormat(format);
    return df.format((int)(num * Math.pow(10, places)) / (double) Math.pow(10, places));
}

然后你可以将它用于任何小数位:

System.out.println(format(1, 2)); // 1.00
System.out.println(format(234, 2)); // 234.00
System.out.println(format(-55.12345, 2)); // -55.12
System.out.println(format(7.2, 2)); // 7.20
相关问题