Java printf()中的数字是什么意思?

时间:2015-04-29 00:15:49

标签: java string-formatting

当我在java中看到这个时,我知道.2是小数位,f是浮点数,n是换行符等等。但是6是什么?

{{1}}

1 个答案:

答案 0 :(得分:0)

It stands for the length of the string that is returned by the printf method. So in this case a string that is at least 6 characters long.

Which means that if

someDouble=pi

then

System.out.printf("%6.2f2%n", someDouble);

will print out the string

"  3.14"

(i.e. 2 whitespaces followed by 4 characters containing 3.14)

Another example would be

System.out.printf("%2.2f2%n", someDouble);

Which prints out

"3.14"

We can see from this that this does not override the .2 or anything else in this command if a shorter value is given than is needed for other rules to apply.

So this only makes sure there is extra whitespace preceding the value.