将前导零添加到字符串

问题描述:

我想在字符串中添加一些前导零,总长度必须为8个字符.例如:

I want to add some leading zeroes to a string, the total length must be eight characters. For example:

123应该是00000123
1243应该是00001234
123456应该是00123456
12345678应该是12345678

123 should be 00000123
1243 should be 00001234
123456 should be 00123456
12345678 should be 12345678

最简单的方法是什么?

俗气的小把戏

String str = "123";
String formatted = ("00000000" + str).substring(str.length())

如果您改用数字开头:

Int number = 123;
String formatted = String.format("%08d", number);