bytesAsReadable method

String bytesAsReadable(
  1. int bytes, {
  2. bool pad = true,
})

returns the the number of bytes in a human readable form. e.g. 1e+5 3.000T, 10.00G, 100.0M, 20.00K, 10B

When pad is true Except for absurdly large no. (> 10^20) the return is guarenteed to be 6 characters long. For no. < 9999 we right pad the no. with spaces.

When pad is false Except for absurdly large no. (> 10^20) the return is guarenteed to be 6 or less characters long. Returns bytes in a human-readable binary form (base 1024). Examples: 3.000T, 10.00G, 100.0M, 20.00K, 10B

With pad true (default), the numeric part is left-padded to width 5, so the whole string is 6 chars incl. the unit (except when using scientific notation for very large values).

Implementation

String bytesAsReadable(int bytes, {bool pad = true}) {
  // Switch to scientific notation from 1 PiB (i.e., 1024^5).
  const petaBytes = 1125899906842624;
  if (bytes >= petaBytes) {
    return bytes.toStringAsExponential(0);
  }

  const units = ['B', 'K', 'M', 'G', 'T'];
  var value = bytes.toDouble();
  var unitIndex = 0;

  // Binary (1024) steps.
  while (value >= 1024 && unitIndex < units.length - 1) {
    value /= 1024;
    unitIndex++;
  }

  String numberPart;
  if (unitIndex == 0) {
    // Bytes: integer, pad to width 5 if requested.
    numberPart = value.toInt().toString();
    if (pad) {
      numberPart = numberPart.padLeft(5);
    }
  } else {
    // For K and above, choose decimals so numeric part is exactly 5 chars.
    final intLen = value.floor().toString().length;
    var decimals = 5 - intLen - 1; // reserve 1 for '.'
    if (decimals < 0) {
      decimals = 0;
    }

    numberPart = value.toStringAsFixed(decimals);

    // Ensure exactly 5 chars for the numeric field.
    if (numberPart.length > 5) {
      numberPart = numberPart.substring(0, 5);
      // Avoid trailing '.' if trimming lands on it.
      if (numberPart.endsWith('.')) {
        numberPart = numberPart.substring(0, 4);
      }
    } else if (pad) {
      numberPart = numberPart.padLeft(5);
    }
  }

  return '$numberPart${units[unitIndex]}';
}