Flutter/Dart How to: Different ways to add leading trailing zeroes to number| Dart By Example
This tutorial demonstrates multiple methods to add leading zeroes to an integer number in Dart/Flutter programming.
How to add leading zeroes to integer numbers using left and right padding? How to prefix and suffix zeroes to a number in Dart? How to add leading and trailing zeroes to a number?
How to Add Leading Zeroes to an Integer Number
A leading zero is a zero added to an integer number, either on the left or right side, to achieve a specific length.
Consider a length of 8. Given the number 111, the output should be 00000111.
There are several approaches to add padded zeroes to a given number.
Using the padLeft Method of the String Class
The padLeft
method of the String
class adds left padding to a string with a given character and length.
String padLeft(int width, [String padding = ' '])
width
specifies the total length.padding
is an optional character used for padding (defaults to empty if not provided).
Example:
void main() {
print(111.toString().padLeft(8, '0')); // Output: 00000111
}
Output:
00000111
Using the NumberFormat Class from the intl Package
The intl/intl.dart
package offers number formatting utilities.
To use it:
- Import the
intl/intl.dart
package into your program. - Create a
NumberFormat
instance with the desired format, including zeroes. - Use the
format()
method to format the given number.
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 a length of 8. Given the number 111, the output should be 11100000.
The padRight
method of the String
class adds right padding with the specified character and length.
String padRight(int width, [String padding = ' '])
void main() {
print(111.toString().padRight(8, '0')); //11100000
}
Conclusion
In conclusion, you’ve learned how to add left and right padded zeroes to a given number.