formatNumber method

String formatNumber(
  1. double number
)

Formats and add symbols (K, M, B) at the end of number.

if number is larger than billion, it returns a short number like 13.3B, if number is larger than million, it returns a short number line 43M, if number is larger than kilo, it returns a short number like 4K, otherwise it returns number itself. also it removes .0, at the end of number for simplicity.

Implementation

String formatNumber(double number) {
  final isNegative = number < 0;

  if (isNegative) {
    number = number.abs();
  }

  String resultNumber;
  String symbol;
  if (number >= billion) {
    resultNumber = (number / billion).toStringAsFixed(1);
    symbol = 'B';
  } else if (number >= million) {
    resultNumber = (number / million).toStringAsFixed(1);
    symbol = 'M';
  } else if (number >= kilo) {
    resultNumber = (number / kilo).toStringAsFixed(1);
    symbol = 'K';
  } else {
    resultNumber = number.toStringAsFixed(1);
    symbol = '';
  }

  if (resultNumber.endsWith('.0')) {
    resultNumber = resultNumber.substring(0, resultNumber.length - 2);
  }

  if (isNegative) {
    resultNumber = '-$resultNumber';
  }

  if (resultNumber == '-0') {
    resultNumber = '0';
  }

  return resultNumber + symbol;
}