繁体   English   中英

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

[英]How to print up to 2 digits after the decimal point?

我在打印格式方面有一个小问题。 如果数字不是整数(例如55.53467-> 55.53),我想在小数点后打印两位数;如果数字是整数或在小数点后有一个舍入数字(例如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());
}

但是它当然总是打印两位数。 非常感谢

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

您可能要利用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM