Mayur Prajapati
Mayur Prajapati

Reputation: 627

Convert a number to Human readable format (e.g. 1.5k, 5m, 1b) in 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.

Upvotes: 31

Views: 21109

Answers (2)

Amit Jangid
Amit Jangid

Reputation: 2889

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

Upvotes: 82

Nadeem Abbas
Nadeem Abbas

Reputation: 15

Make a class and used its static method every where.

class NumberFormatter{
  static String formatter(String currentBalance) {
    try{
      // suffix = {' ', 'k', 'M', 'B', 'T', 'P', 'E'};
      double value = double.parse(currentBalance);

      if(value < 1000000){ // less than a million
        return value.toStringAsFixed(2);
      }else if(value >= 1000000 && value < (1000000*10*100)){ // less than 100 million
        double result = value/1000000;
        return result.toStringAsFixed(2)+"M";
      }else if(value >= (1000000*10*100) && value < (1000000*10*100*100)){ // less than 100 billion
        double result = value/(1000000*10*100);
        return result.toStringAsFixed(2)+"B";
      }else if(value >= (1000000*10*100*100) && value < (1000000*10*100*100*100)){ // less than 100 trillion
        double result = value/(1000000*10*100*100);
        return result.toStringAsFixed(2)+"T";
      }
    }catch(e){
      print(e);
    }
  }
}

Upvotes: -8

Related Questions