Add leading zeroes to number in Dart

Dart

Dart Problem Overview


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

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

What is an easy way to do this in Dart?

Dart Solutions


Solution 1 - Dart

DartPad

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

Solution 2 - Dart

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKasperView Question on Stackoverflow
Solution 1 - DartGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - DartTom RoggeroView Answer on Stackoverflow