Skip to content

Instantly share code, notes, and snippets.

@zzpmaster
Last active June 4, 2024 23:11
Show Gist options
  • Save zzpmaster/ec51afdbbfa5b2bf6ced13374ff891d9 to your computer and use it in GitHub Desktop.
Save zzpmaster/ec51afdbbfa5b2bf6ced13374ff891d9 to your computer and use it in GitHub Desktop.
convert bytes to kb mb in dart
static String formatBytes(int bytes, int decimals) {
if (bytes <= 0) return "0 B";
const suffixes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
var i = (log(bytes) / log(1024)).floor();
return ((bytes / pow(1024, i)).toStringAsFixed(decimals)) +
' ' +
suffixes[i];
}
@mc-stephen
Copy link

Thanks alot for this bud, you really did us well

@Coimbra1984
Copy link

See https://en.wikipedia.org/wiki/Binary_prefix, to be fully compliant, factor 1024 requires abbreviations ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"], also note that in offical SI-Notation kB (kilo byte) has a lower case k, while KiB has not.

String formatBytes(int bytes, int decimals, bool binaryPrefixes) {
if (bytes <= 0) return "0 B";
int fac = 1000;
List suffixes = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
if (binaryPrefixes) {
fac = 1024;
suffixes = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
}

var i = (log(bytes) / log(fac)).floor();
i = i >= (suffixes.length - 1) ? suffixes.length - 1 : i;
return '${(bytes / pow(fac, i)).toStringAsFixed(decimals)} ${suffixes[i]}';
}

@RoyalCoder88
Copy link

thanks a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment