toFileSize method

String toFileSize({
  1. int decimals = 1,
})

Converts the number to a human-readable file size string.

Example:

1024.0.toFileSize(); // '1.0 KB'
1048576.0.toFileSize(); // '1.0 MB'

Implementation

String toFileSize({int decimals = 1}) {
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  var size = this;
  var unitIndex = 0;

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

  return '${size.formatAsString(decimals)} ${units[unitIndex]}';
}