问题
Why does
System.out.format("%03.3f", 1.23456789);
print 1.235
instead of 001.235
?
How has my format
string to look like to get 001.235
as output of the following code line?
System.out.format(format, 1.23456789);
回答1:
Number after %0
here defines full width including decimal point, so you need to change it to 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
Demo
来源:https://stackoverflow.com/questions/30081930/format-floating-point-number-with-leading-zeros