Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number to Human readable format (e.g. 1.5k, 5m, 1b) in Dart?

Tags:

flutter

dart

i'm developing an app related to social messanging and i want to convert big numbers to Human readable format (e.g. 1500 to 1.5k) and also i'm new to Dart. Your help will be appreciated.

like image 615
Mayur Prajapati Avatar asked Feb 14 '19 12:02

Mayur Prajapati


1 Answers

You can use the NumberFormat class of flutter which has some in built functions for results you want..

Check out this link for NumberFormat class of flutter

Example: This is one way if you want to use currency..

var _formattedNumber = NumberFormat.compactCurrency(
  decimalDigits: 2,
  symbol: '', // if you want to add currency symbol then pass that in this else leave it empty.
).format(numberToFormat);

print('Formatted Number is: $_formattedNumber');

Example: This example is with locale.

var _formattedNumber = NumberFormat.compactCurrency(
  decimalDigits: 2,
  locale: 'en_IN'
  symbol: '',
).format(numberToFormat);

print('Formatted Number is: $_formattedNumber');

The output of this is code would be:

If 1000 is entered then 1K is the output

Another way is by just using NumberFormat.compact() which gives the desired output...

// In this you won't have to worry about the symbol of the currency.
var _formattedNumber = NumberFormat.compact().format(numberToFormat);
print('Formatted Number is: $_formattedNumber');

The output of above example will also be:

If 1000 is entered then 1K is the output

I tried this and is working...

like image 71
Amit Jangid Avatar answered Sep 28 '22 03:09

Amit Jangid