This tutorial shows multiple ways to add leading zeroes to an integer number in Dart/Flutter programming.
This talks about multiple examples of the below things.
- How to add left and right pad zeroes to integer numbers?
- prefix and suffix zeroes to number in dart
- leading and trailing zeroes to a number
How to add lead zeroes to Integer Number
Leading zero is a zero added to integer number with a given specific length on the left side or right side of a given number digits
Consider, length is 8, Given Number 111 and output is 00000111.
There are several ways to add pad zeroes to a given number.
use String padLeft method
String.padLeft(length,character) methods adds the left pad given character
to given string with length
.
String padLeft(int width, [String padding = ' '])
width
is the total length
padding
is default optional empty if not provided value.
Example:
void main() {
print(111.toString().padLeft(8, '0')); //00000111
}
Output:
00000111
use NumberFormat format method
intl/intl.dart
package provides Number formatting utilities.
First, Import intl/intl.dart
package into program.
Next, Create NumberFormat with a format of zeroes with a length of 6.
formatter.format()
formats the given number as per the format
Here is an example
import 'package:intl/intl.dart';
void main() {
NumberFormat formatter = new NumberFormat("000000");
print("${formatter.format(111)}"); //000111
}
Output:
000111
How to add trailing zeroes to an integer number
Consider, length is 8, Given Number 111, and output is 11100000.
String.padLeft(length,character)
methods adds the right pad given character
to given string with length
.
String padLeft(int width, [String padding = ' '])
void main() {
print(111.toString().padRight(8, '0')); //11100000
}
Conclusion
As a Result, Learn how to add left and right pad zero to a given number.