{

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


Format a currency number in Dart and Flutter

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

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart Example - Program to check Leap year or not

Dart Example to count the number of digits in a number| Decimals Count in Dart