How to format a file size in Dart?
Input: 1000000
Expected output: 1 MB
The input could be either an int or a double for ease of use, and the result should be a String with only one decimal.
I made an extension method for this:
extension FileFormatter on num {
String readableFileSize({bool base1024 = true}) {
final base = base1024 ? 1024 : 1000;
if (this <= 0) return "0";
final units = ["B", "kB", "MB", "GB", "TB"];
int digitGroups = (log(this) / log(base)).round();
return NumberFormat("#,##0.#").format(this / pow(base, digitGroups)) +
" " +
units[digitGroups];
}
}
You will need to use the intl package for the NumberFormat class.
You can display bits or bytes using the boolean base64.
Usage:
int myInt = 12345678;
double myDouble = 2546;
print('myInt: ${myInt.readableFileSize(base1024: false)}');
print('myDouble: ${myDouble.readableFileSize()}');
Output:
myInt: 12.3 MB
myDouble: 2.5 kB
Inspired by this SO answer.