formatBytesToHuman function
Formats a byte count in bytes into a human-readable size string.
Scales by 1024 through the suffixes B, KB, ..., EB, using up to
decimals fractional digits with trailing zeros trimmed. Whole values and
values 10 or larger are shown without decimals. Zero yields 0 B; negative
counts are prefixed with -.
Example:
formatBytesToHuman(1572864); // '1.5 MB'
formatBytesToHuman(0); // '0 B'
Implementation
String formatBytesToHuman(int bytes, {int decimals = 1}) {
if (bytes < 0) return '-${formatBytesToHuman(-bytes, decimals: decimals)}';
if (bytes == 0) return _kSizeZeroB;
int i = 0;
double v = bytes.toDouble();
while (v >= 1024 && i < _sizeSuffixes.length - 1) {
v /= 1024;
i++;
}
final String formatted = v >= 10 || v == v.truncateToDouble()
? v.truncate().toString()
: v.toStringAsFixed(decimals).replaceAll(RegExp(r'0+$'), '').replaceAll(RegExp(r'\.$'), '');
return '$formatted ${_sizeSuffixes[i]}';
}