toCompact method

String toCompact({
  1. int digits = 1,
})

Returns a compact, human-readable representation of this number.

The number is scaled by powers of 1000 and suffixed with a unit letter (K, M, B, T for thousand, million, billion, trillion).

digits controls the number of fractional digits (default: 1).

1234.toCompact();          // "1.2K"
1234567.toCompact();       // "1.2M"
999.toCompact();           // "999"
(-1500).toCompact();       // "-1.5K"
1500.toCompact(digits: 2); // "1.50K"

Implementation

String toCompact({int digits = 1}) {
  if (this == 0) return '0';
  final negative = this < 0;
  var value = negative ? -this : this;
  const suffixes = ['', 'K', 'M', 'B', 'T'];
  var index = 0;

  while (value >= 1000 && index < suffixes.length - 1) {
    value /= 1000;
    index++;
  }

  if (index == 0) {
    return '${negative ? '-' : ''}${value.toStringAsFixed(0)}';
  }

  return '${negative ? '-' : ''}${value.toStringAsFixed(digits)}${suffixes[index]}';
}