在 Dart 中将前导零添加到数字

我想给一个字符串加几个前导零。例如,总长度可能是8个字符。例如:

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

在达特,有什么简单的方法可以做到这一点?

39386 次浏览

DartPad

void main() {
print(123.toString().padLeft(10, '0'));
}

Using NumberFormat from 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)}");

Result:

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