-
-
Save zzpmaster/ec51afdbbfa5b2bf6ced13374ff891d9 to your computer and use it in GitHub Desktop.
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]; | |
} |
This works perfectly! Thanks
Thanks, very useful for me!!
Thanks :)
Its not accurate.
With 4351231
bytes it returns 4.15MB
instead of 4.35MB
@giacomok The factor is 1024
and not 1000
.
Thank you so much!!
Cool ❤
Yep Nice! Thanks.
Perfect
thank you
thank you
Thank you! This was really helpful.
I was also facing the same issue as @erperejildo mentioned. So I used 1000
instead of 1024
.
Edit: just realised @LostInDarkMath mentioned it in his comment. Thanks!
Nice!
Thanks :)
Thanks, very handy!
Thanks alot for this bud, you really did us well
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]}';
}
thanks a lot
Very nice! Thank You <3