使用前导零格式化浮点数

pri*_*ain 10 java string-formatting

为什么

System.out.format("%03.3f", 1.23456789);
Run Code Online (Sandbox Code Playgroud)

打印1.235而不是001.235

我的format字符串看起来如何得到001.235以下代码行的输出?

System.out.format(format, 1.23456789);
Run Code Online (Sandbox Code Playgroud)

Ale*_*you 15

此后的数字%0定义包括小数点的全宽,因此您需要将其更改为7:

System.out.format("%07.3f", 1.23456789);
Run Code Online (Sandbox Code Playgroud)