Skip to content

Commit 862cb5c

Browse files
committed
Improve bytes
1 parent 1a36a44 commit 862cb5c

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

lib/src/utils/helpers.dart

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
// Helper functions for validator and sanitizer.
22

3+
import 'dart:math';
4+
5+
import 'package:intl/intl.dart';
6+
37
T shift<T>(List<T> l) {
48
if (l.isNotEmpty) {
59
final first = l.first;
@@ -26,14 +30,18 @@ String fileExtensionFromPath(String path) {
2630
}
2731

2832
/// Helper function to format bytes into a human-readable string (e.g., KB, MB, GB).
29-
String formatBytes(int bytes) {
30-
const suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];
31-
var i = 0;
32-
double size = bytes.toDouble();
33-
while (size > 1024 && i < suffixes.length - 1) {
34-
size /= 1024;
35-
i++;
36-
}
37-
// Truncate to 1 decimal place
38-
return '${size.toStringAsFixed(1)}${suffixes[i]}';
33+
String formatBytes(int bytes, {bool base1024 = true}) {
34+
double log10(num x) => log(x) / ln10;
35+
36+
if (bytes <= 0) return "0 B";
37+
38+
final base = base1024 ? 1024 : 1000;
39+
final units = base1024
40+
? ["B", "KiB", "MiB", "GiB", "TiB"]
41+
: ["B", "kB", "MB", "GB", "TB"];
42+
43+
int digitGroups = (log10(bytes) / log10(base)).floor();
44+
double size = bytes / pow(base, digitGroups);
45+
46+
return "${NumberFormat("#,##0.#").format(size)} ${units[digitGroups]}";
3947
}

0 commit comments

Comments
 (0)