我想在字符串中添加一些前导零。例如,总长度可以是八个字符。例如:
123 should be 00000123
1243 should be 00001234
123456 should be 00123456
12345678 should be 12345678
在Dart中执行此操作的简单方法是什么?
答案 0 :(得分:19)
void main() {
print(123.toString().padLeft(10, '0'));
}
答案 1 :(得分:4)
使用NumberFormat
中的import 'package:intl/intl.dart';
NumberFormat formatter = new NumberFormat("00000000");
// The following outputs your expected output
debugPrint("123 should be ${formatter.format(123)}");
debugPrint("1243 should be ${formatter.format(1243)}");
debugPrint("123456 should be ${formatter.format(123456)}");
debugPrint("12345678 should be ${formatter.format(12345678)}");