formatFileSize function
Formats bytes as a human-readable size using binary (1024) units up to TB.
decimals controls the maximum fraction digits; trailing zeros are
trimmed. Whole values and sizes of 10 or more drop the fraction. Negative
inputs are prefixed with -.
Example:
formatFileSize(1536); // '1.5 KB'
formatFileSize(0); // '0 B'
Audited: 2026-06-12 11:26 EDT
Implementation
String formatFileSize(int bytes, {int decimals = 1}) {
if (bytes < 0) return '-${formatFileSize(-bytes, decimals: decimals)}';
if (bytes == 0) return _kSizeZeroB;
const List<String> units = _kFileSizeUnits;
int i = 0;
double v = bytes.toDouble();
while (v >= 1024 && i < units.length - 1) {
v /= 1024;
i++;
}
String fmt;
if (v >= 10 || v == v.truncateToDouble()) {
fmt = v.truncate().toString();
} else {
fmt = v.toStringAsFixed(decimals);
// Strip trailing zeros only AFTER a decimal point. With decimals: 0,
// toStringAsFixed rounds (9.5 -> "10") and produces no '.', so the bare
// `0+$` strip turned "10" into "1" — wrong magnitude. Guarding on '.' keeps
// integer-part zeros.
if (fmt.contains('.')) {
fmt = fmt.replaceAll(RegExp(r'0+$'), '').replaceAll(RegExp(r'\.$'), '');
}
}
return '$fmt ${units[i]}';
}