java - 为什么 `%4.` 在我的号码中添加空格?

标签 java string formatting format string-formatting

我有这个代码:

private String padWithZeroRightToPeriod(String serverFormat, float unformattedNumber, int index) {
    int nDigits = getNumberOfDigitsAfterPeriod(serverFormat);
    String floatingFormat = "%4." + nDigits + "f";
    String formattedPrice = String.format(floatingFormat, unformattedNumber);

当调用unformattedNumber846时,为什么结果是“846”(一个空格,然后是三个数字)?

%4. 是什么意思?

最佳答案

docs for String.format请您参阅this documentation on format strings ,其中表示:

The format specifiers for general, character, and numeric types have the following syntax:

%[argument_index$][flags][width][.precision]conversion

The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.

The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion.

The optional width is a positive decimal integer indicating the minimum number of characters to be written to the output.

The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion.

The required conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.

从您的示例输出来看,getNumberOfDigitsAfterPeriod 似乎正在返回 0,因此您的格式字符串为 %4.0f。所以:

  • 它没有参数索引(4后面没有$)
  • 它有一个宽度 (4)
  • 它具有精度 (0)
  • 当然它有一个转换 (f)

因此 846 输出为 "846" 因为宽度为 4。所讨论的宽度是输出的字符总数。这是一个不同的示例:Live Copy

public class Example {

    public static void main(String args[]) {
        System.out.println(String.format("%8.2f", 846.0));
        System.out.println(String.format("%8.2f", 42.4));
    }
}

输出:

  846.00
   42.40

请注意,每个字符长为八个字符。

关于java - 为什么 `%4.` 在我的号码中添加空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24350023/

相关文章:

java - 当我将元素从一个包移动到另一个包时出现 ObjectDeletedException

java - 如何在java中的bat文件中提供相对URL

php - 获取自 mysql 查询中特定日期以来的小时数

ruby - 在 Ruby 中格式化一个 xml 字符串

java - 错误 IllegalStateException 在为大型数据集提交响应后无法创建 session

java - 无法使用运行时 exec 访问环境变量

c++ - 将字符串转换为长

java - 如何使用 BeanUtils.populate 方法从 String[] 转换为 ArrayList<String>?

c++ - 如何返回目录的末尾

Excel 宏 : how do I change all row heights, 但是如果 cell.value = bold 会使单元格高度变大?