{

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 instance.

Call format() method with input and format number with align 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
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.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example