Last active
June 4, 2024 23:11
-
-
Save zzpmaster/ec51afdbbfa5b2bf6ced13374ff891d9 to your computer and use it in GitHub Desktop.
convert bytes to kb mb in dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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]}';
}