在 Dart 中格式化文件大小

问题描述 投票:0回答:2

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

输入:1000000

预期输出:1 MB

输入可以是

int
double
,以便于使用,结果应该是
String
,只有一位小数。

flutter dart format filesize
2个回答
7
投票

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

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答案的启发


0
投票

由于以上都不能让我满意,所以我将这个函数转换为更易于阅读、更灵活的版本:

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  
© www.soinside.com 2019 - 2024. All rights reserved.