asGreeks method

String asGreeks([
  1. int zerosFractionDigits = 0,
  2. int fractionDigits = 1
])

Converts a number to a string with Greek symbols for thousands, millions, etc.

Example usage: print(1000.asGreeks); // Output: 1.0K print(1500000.asGreeks); // Output: 1.5M print(2500000000.asGreeks); // Output: 2.5B

Implementation

String asGreeks([int zerosFractionDigits = 0, int fractionDigits = 1]) {
  if (this < 1000) {
    return zerosFractionDigits <= 0
        ? toInt().toString()
        : toStringAsFixed(zerosFractionDigits);
  }

  var magnitude = 0;
  var reducedNum = this;
  while (reducedNum >= 1000 && magnitude < greekNumberSuffixes.length) {
    reducedNum /= 1000;
    magnitude++;
  }

  final symbol = magnitude > 0 ? greekNumberSuffixes[magnitude - 1] : '';

  return fractionDigits <= 0
      ? '${reducedNum.toInt()}$symbol'
      : '${reducedNum.toStringAsFixed(fractionDigits)}$symbol';
}