formatBytes static method

String formatBytes(
  1. num? bytes, [
  2. int decimals = 2
])

Implementation

static String formatBytes(num? bytes, [int decimals = 2]) {
  if (bytes == null || bytes <= 0) return "0 B";
  const suffixes = ["B", "KB", "MB", "GB", "TB", "PB"];
  final safeDecimals = decimals.clamp(0, 20).toInt();
  int i = 0;
  double size = bytes.toDouble();

  while (size >= 1000 && i < suffixes.length - 1) {
    size /= 1000;
    i++;
  }

  return "${size.toStringAsFixed(safeDecimals)} ${suffixes[i]}";
}