Format floating point number with leading zeros [duplicate]

…衆ロ難τιáo~ 提交于 2019-12-04 02:59:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!