toCompactString method

  1. @useResult
String toCompactString({
  1. int decimals = 1,
})

Formats as compact string (e.g. 1200 → "1.2K", 1500000 → "1.5M").

decimals is the max decimal places for the fractional part.

Implementation

@useResult
String toCompactString({int decimals = 1}) {
  final double n = toDouble().abs();
  const List<String> suffixes = <String>['', 'K', 'M', 'B', 'T'];
  int i = 0;
  double v = n;
  while (v >= 1000 && i < suffixes.length - 1) {
    v /= 1000;
    i++;
  }
  final String formatted = v >= 10 || v == v.truncateToDouble()
      ? v.truncate().toString()
      : v.toStringAsFixed(decimals).replaceAll(RegExp(r'0+$'), '').replaceAll(RegExp(r'\.$'), '');
  final String sign = this < 0 ? '-' : '';
  return '$sign$formatted${suffixes[i]}';
}