How to Format a currency Dart or Flutter | Dart By Example

In Dart, You have a class NumberFormat that formats numbers with currency formats of a different locale.

For example, if a given number is 100000, Some countries allow you to format a number as 100,000 and 100,000.00.

Dart NumberFormat example

Numberformat is a class in the intl package.

First, define dependency in pubspec.yaml

dev_dependencies:
    intl: any

Next, Install dependency using the dart pub get command in the terminal or It automatically downloads in the Visual studio terminal

intl.dart package provides NumberFormat class that formats the number as per Locale.

First, create an object of NumberFormat.

NumberFormat NumberFormat([String? newPattern, String? locale])

newpattern is a format of the number and Locale is a valid locale string. NumberFormat.format() method formats number as per pattern.

How to format a number with group separator for Currency in Dart?

In this section, You will format the currency number as per Locale. NumberFormat object provided with a pattern of commas and decimal format.

here is an example program

import 'package:intl/intl.dart';

final numberFormat = new NumberFormat("##,##0.00", "en_US");

void main() {
  print(numberFormat.format(1000000.10));
}

How to format numbers with 5 decimals length

Here numberformat is provided with 5 zeroes and local here is an example program

import 'package:intl/intl.dart';

final numberFormat = new NumberFormat("#####.000000", "en_US");

void main() {
  print(numberFormat.format(1000000.10));
}

Output:

1000000.100000

How to align currency to number in dart

NumberFormat.currency() method takes locale and Symbol string and creates an instance.

Call format() method with input and format number with aligned currency symbol based on current locale.

import 'package:intl/intl.dart';

final numberFormat = NumberFormat.currency(locale: 'en_US', symbol: 'USD');

void main() {
  print(numberFormat.format(3421231));
}

Output:

USD3,421,231.00