This question already has an answer here:
这个问题在这里已有答案:
- printf how to do floating points with leading zeros 3 answers
printf如何用前导零3个答案做浮点数
Why does
System.out.format("%03.3f", 1.23456789);
print 1.235
instead of 001.235
?
打印1.235而不是001.235?
How has my format
string to look like to get 001.235
as output of the following code line?
我的格式字符串如何将001.235作为以下代码行的输出?
System.out.format(format, 1.23456789);
2 个解决方案
#1
Number after %0
here defines full width including decimal point, so you need to change it to 7
:
此后%0之后的数字定义包括小数点的全宽,因此您需要将其更改为7:
System.out.format("%07.3f", 1.23456789);
#2
DecimalFormat formatter = (DecimalFormat)NumberFormat.getNumberInstance(Locale.US);
formatter.applyPattern("000.###");
System.out.format(formatter.format(1.23456789));
Result:
001.234
#1
Number after %0
here defines full width including decimal point, so you need to change it to 7
:
此后%0之后的数字定义包括小数点的全宽,因此您需要将其更改为7:
System.out.format("%07.3f", 1.23456789);
#2
DecimalFormat formatter = (DecimalFormat)NumberFormat.getNumberInstance(Locale.US);
formatter.applyPattern("000.###");
System.out.format(formatter.format(1.23456789));
Result:
001.234