java - System.out.format 的输出 ("%6f%n", 123.0);不符合预期

标签 java format

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

我有

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

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

123.000000 //with no blank space on the left 

为什么会发生这种情况?为什么小数点后有六个0?有人可以向我解释一下吗?

最佳答案

您需要指定小数点后面的位数。如果不这样做,则假定为 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.

关于java - System.out.format 的输出 ("%6f%n", 123.0);不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41009137/

相关文章:

java - 使用 Spock (groovy) 数据表测试没有参数的方法

java - keyCode == KeyEvent.KEYCODE_BUTTON_Y 卡住焦点并且之后无法导航

java - 检索路径中最后一个子字符串和最后一个子字符串之前的子字符串

Android DatePickerDialog 标题问题

java - 电子邮件中 ​​html 正文中的嵌入图像(内联)显示为附件

java - 我无法使用 Reddit 的 API 登录

c - 读取一串预期模式

mysql - SQL TIME 更改数据库中的格式?

php - 格式化金额为数据库格式

parsing - 解码 GPS 数据 - 不知道格式是什么