【问题标题】:How to print up to 2 digits after the decimal point?如何打印小数点后最多2位?
【发布时间】:2016-03-16 20:21:00
【问题描述】:

我在打印格式上有一个小问题。 如果数字,我想在小数点后打印 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 位数字。 非常感谢

【问题讨论】:

  • “当然,它总是打印两位数。”然后改变它。使用if/else 逻辑。
  • 为什么?为什么不直接说 2.00 以保持统一?如果参数是“第二个零不添加任何东西”,那么可以肯定,但第一个也不会。如果要显示公式,“2x + 4.3y”有意义,“2.0x + 4.3y”没有意义。

标签: java


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多