如何将数字格式化为相同的数字,0-padded?
我有几个不同长度的字符串
"2323" "245" "353352"
我需要将它们转换为相同大小的字符串,例如:
"0002323" "0000245" "0353352"
如何在每个字符串前面自动添加正确数量的0?
谢谢
使用String.format
:
Integer i = Integer.valueOf(src); String format = "%1$07d"; String result = String.format(format, i);
使用DecimalFormat
, String.format
或printf
可以格式化数字。
使用DecimalFormat的示例:
NumberFormat formatter = new DecimalFormat("0000000"); String number = formatter.format(2500);
希望能帮助到你。
问候!
或者使用Apache Commons / Lang :
String s = "245"; String zeroPadded = StringUtils.leftPad(s, 6, '0');
参考:
-
StringUtils.leftPad(String, length, padChar)