实际开发中经常遇到数字位数不够时前面补0的需求,比如:
- 1 -> 001
- 12 -> 012
- 123 -> 123
方案一:
使用 padLeft
:
print(1.toString().padLeft(3, '0')); // 001
print(12.toString().padLeft(3, '0')); // 012
print(123.toString().padLeft(3, '0')); // 123
print(1234.toString().padLeft(3, '0')); // 1234
方案二:
使用 NumberFormat
:
NumberFormat formatter = NumberFormat("000");
print(formatter.format(1)); // 001
print(formatter.format(12)); // 012
print(formatter.format(123)); // 123
print(formatter.format(1234)); // 1234