如何在Dart中格式化文件大小?
输入:1000000
期望输出:1 MB
为方便使用,输入可以是int
或double
,结果应该是一个只有一位小数的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
double log10(final num x) => log(x) / ln10;
。2)四舍五入不够精确,使用.floor()
将会得到期望的结果。 - Noah Anderson