Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert large number to shorten K/M/B in Dart

Tags:

dart

How can I create function that convert large number into shorten number with character in Dart?

like

1000 => 1K
10000 => 10K
1000000 => 1M
10000000 => 10M
1000000000 => 1B
like image 638
Daibaku Avatar asked Nov 25 '25 23:11

Daibaku


1 Answers

There is a built-in function in Dart that can be used and it's simple:

var f = NumberFormat.compact(locale: "en_IN");
print(f.format(12345));

to make it a method:

getShortForm(var number) {
  var f = NumberFormat.compact(locale: "en_US");
  return f.format(number);
}

for this to work import

import 'package:intl/intl.dart';

Refer to this doc for more https://pub.dev/documentation/intl/latest/intl/NumberFormat-class.html

If you are looking for a hard way:

getShortForm(int number) {
  var shortForm = "";
  if (number != null) {
    if (number < 1000) {
      shortForm = number.toString();
    } else if (number >= 1000 && number < 1000000) {
      shortForm = (number / 1000).toStringAsFixed(1) + "K";
    } else if (number >= 1000000 && number < 1000000000) {
      shortForm = (number / 1000000).toStringAsFixed(1) + "M";
    } else if (number >= 1000000000 && number < 1000000000000) {
      shortForm = (number / 1000000000).toStringAsFixed(1) + "B";
    }
  }
  return shortForm;
}
like image 156
Sanjay TM Avatar answered Nov 28 '25 14:11

Sanjay TM