我有这个代码:
private String padWithZeroRightToPeriod(String serverFormat, float unformattedNumber, int index) {
int nDigits = getNumberOfDigitsAfterPeriod(serverFormat);
String floatingFormat = "%4." + nDigits + "f";
String formattedPrice = String.format(floatingFormat, unformattedNumber);
当调用unformattedNumber
为846
时,为什么结果是“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/