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

Viewed 2715

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

3 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();
      }
    }

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);
}

The answer is not entirely correct. If you test it, you will see what i meant. Base on the answer above, I created this solution:

String numberFormat(int n) {
  String num = n.toString();
  int len = num.length;

  if (n >= 1000 && n < 1000000) {
    return num.substring(0, len - 3) + '.' + num.substring(len - 3, 1 + (len - 3)) + 'k';
  } else if (n >= 1000000 && n < 1000000000) {
    return num.substring(0, len - 6) + '.' + num.substring(len - 6, 1 + (len - 6)) + 'm';
  } else if (n > 1000000000) {
    return num.substring(0, len - 9) + '.' + num.substring(len - 9, 1 + (len - 9)) + 'b';
  } else {
    return num.toString();
  }
}
Related