{

Flutter/Dart How to: Different ways to add leading trailing zeroes to number| Dart By Example


how to add left right pad zeroes to a number in dart or flutter

This tutorial shows multiple ways to add leading zeroes to an integer number in Dart/Flutter programming.

  • 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 an integer number with a given specific length on the left side or right side of a given number of digits

Consider, the length is 8, Given the Number 111 and the output is 00000111.

There are several ways to add pad zeroes to a given number.

use the String padLeft method

String.padLeft(length, character) methods add the left pad given character to the 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 a NumberFormat format method

The intl/intl.dart package provides Number formatting utilities.

First, Import the intl/intl.dart package into the 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, the length is 8, Given Number 111, and the output is 11100000.

The String.padLeft(length, character) method adds the right pad given character to the 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.