以Dart格式设置文件大小



如何在Dart中格式化文件大小?

输入:1000000

期望输出:1mb

为了方便使用,输入可以是intdouble,结果应该是只有一个小数的String

我为此做了一个扩展方法:

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];
}
}

你需要为NumberFormat类使用intl包。

您可以使用布尔值base64显示位或字节。

用法:

int myInt = 12345678;
double myDouble = 2546;
print('myInt: ${myInt.readableFileSize(base1024: false)}');
print('myDouble: ${myDouble.readableFileSize()}');
输出:

myInt: 12.3 MB
myDouble: 2.5 kB

受这个SO答案的启发。

由于以上这些我都不满意,所以我把这个函数转换成一个更容易阅读、更灵活的版本:

extension FileSizeExtensions on num {
/// method returns a human readable string representing a file size
/// size can be passed as number or as string
/// the optional parameter 'round' specifies the number of numbers after comma/point (default is 2)
/// the optional boolean parameter 'useBase1024' specifies if we should count in 1024's (true) or 1000's (false). e.g. 1KB = 1024B (default is true)
String toHumanReadableFileSize({int round = 2, bool useBase1024 = true}) {
const List<String> affixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
num divider = useBase1024 ? 1024 : 1000;
num size = this;
num runningDivider = divider;
num runningPreviousDivider = 0;
int affix = 0;
while (size >= runningDivider && affix < affixes.length - 1) {
runningPreviousDivider = runningDivider;
runningDivider *= divider;
affix++;
}
String result = (runningPreviousDivider == 0 ? size : size / runningPreviousDivider).toStringAsFixed(round);
//Check if the result ends with .00000 (depending on how many decimals) and remove it if found.
if (result.endsWith("0" * round)) result = result.substring(0, result.length - round - 1);
return "$result ${affixes[affix]}";
}
}

样本输出:

1024 = 1 KB  
800 = 800 B  
8126 = 7.94 KB  
10247428 = 9.77 MB  

相关内容

最新更新