toReadable method
Convert to a human-readable string (e.g. 1234
-> 1.2K
).
fractionDigits
: the (max) number of digits after the decimal point.forceFraction
: force to display fraction digits even if it's zero. iffalse
, trailing zeros will be removed.
Example
10203.toReadable(1); // "10.2K"
10203.toReadable(2); // "10.2K"
10203.toReadable(2, true); // "10.20K"
10203.toReadable(3); // "10.203K"
Implementation
String toReadable([int fractionDigits = 1, bool forceFraction = false]) {
final absVal = abs();
String raw = '';
String unit = '';
switch (absVal) {
case < 1e3:
raw = toStringAsFixed(fractionDigits);
break;
case < 1e6:
raw = (this / 1e3).toStringAsFixed(fractionDigits);
unit = 'K';
break;
case < 1e9:
raw = (this / 1e6).toStringAsFixed(fractionDigits);
unit = 'M';
break;
default:
raw = (this / 1e9).toStringAsFixed(fractionDigits);
unit = 'B';
break;
}
// remove trailing zeros if not forceFraction
if (!forceFraction) raw = raw.replaceAll(RegExp(r'\.?0+$'), '');
return '$raw$unit';
}