有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

系统的java输出。出来格式(“%6f%n”,123.0);不像预期的那样

我目前正在学习如何用java格式化,遇到了以下问题

我有

System.out.format("%6f%n", 123.0);

我希望结果是123.0,左边有一个空格(即输出的最小长度为6)。然而,我得到的却是

123.000000 //with no blank space on the left 

为什么会这样?为什么小数点后有六个0?有人能给我解释一下吗


共 (1) 个答案

  1. # 1 楼答案

    您需要指定小数点后的位数。如果没有,则假定为6位数。所以你可以做:

    System.out.format("%6.1f%n", 123.0);
    

    Javadoc开始:

    The number of digits in the result for the fractional part of m or a is equal to the precision. If the precision is not specified then the default value is 6. If the precision is less than the number of digits which would appear after the decimal point in the string returned by Float.toString(float) or Double.toString(double) respectively, then the value will be rounded using the round half up algorithm. Otherwise, zeros may be appended to reach the precision.