formatFileSize function

String formatFileSize(
  1. int bytes, {
  2. int decimals = 1,
})

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'

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++;
  }
  final String fmt = v >= 10 || v == v.truncateToDouble()
      ? v.truncate().toString()
      : v.toStringAsFixed(decimals).replaceAll(RegExp(r'0+$'), '').replaceAll(RegExp(r'\.$'), '');
  return '$fmt ${units[i]}';
}