Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a number into thousands, millions and billions with dart/flutter?

Tags:

flutter

dart

How to get a number converted into something like this: 12K, 1.5M, 4.2B from a normal number like: 134900.

like image 382
jean davy Nizigama Avatar asked Jun 03 '20 16:06

jean davy Nizigama


2 Answers

This is a minimalist function, of course you'll have to add validation code to verify if the number is valid before executing the function. Otherwise Enjoy ...

void main() {
      double num = 1250;

      var myNumber = k_m_b_generator(num);

      print(myNumber);
    }

    String k_m_b_generator(num) {
      if (num > 999 && num < 99999) {
        return "${(num / 1000).toStringAsFixed(1)} K";
      } else if (num > 99999 && num < 999999) {
        return "${(num / 1000).toStringAsFixed(0)} K";
      } else if (num > 999999 && num < 999999999) {
        return "${(num / 1000000).toStringAsFixed(1)} M";
      } else if (num > 999999999) {
        return "${(num / 1000000000).toStringAsFixed(1)} B";
      } else {
        return num.toString();
      }
    }
like image 167
jean davy Nizigama Avatar answered Oct 17 '22 16:10

jean davy Nizigama


You can use flutter's NumberFormat class with the compact function.

formatNumber(dynamic myNumber) {
    // Convert number into a string if it was not a string previously
    String stringNumber = myNumber.toString();

    // Convert number into double to be formatted.
    // Default to zero if unable to do so
    double doubleNumber = double.tryParse(stringNumber) ?? 0;

    // Set number format to use
    NumberFormat numberFormat = new NumberFormat.compact();

    return numberFormat.format(doubleNumber);
}
like image 33
Kevin Koo Avatar answered Oct 17 '22 16:10

Kevin Koo