Skip to content

Instantly share code, notes, and snippets.

@samtuga1
Created June 24, 2024 14:42
Show Gist options
  • Save samtuga1/1359539c5e9c76253bc5cabddadee216 to your computer and use it in GitHub Desktop.
Save samtuga1/1359539c5e9c76253bc5cabddadee216 to your computer and use it in GitHub Desktop.
A method returns a human readable string representing a file _size
/// A method returns a human readable string representing a file _size
String filesize(dynamic size, [int round = 2]) {
/**
* [size] can be passed as number or as string
*
* the optional parameter [round] specifies the number
* of digits after comma/point (default is 2)
*/
var divider = 1024;
int _size;
try {
_size = int.parse(size.toString());
} catch (e) {
throw ArgumentError('Can not parse the size parameter: $e');
}
if (_size < divider) {
return '$_size B';
}
if (_size < divider * divider && _size % divider == 0) {
return '${(_size / divider).toStringAsFixed(0)} KB';
}
if (_size < divider * divider) {
return '${(_size / divider).toStringAsFixed(round)} KB';
}
if (_size < divider * divider * divider && _size % divider == 0) {
return '${(_size / (divider * divider)).toStringAsFixed(0)} MB';
}
if (_size < divider * divider * divider) {
return '${(_size / divider / divider).toStringAsFixed(round)} MB';
}
if (_size < divider * divider * divider * divider && _size % divider == 0) {
return '${(_size / (divider * divider * divider)).toStringAsFixed(0)} GB';
}
if (_size < divider * divider * divider * divider) {
return '${(_size / divider / divider / divider).toStringAsFixed(round)} GB';
}
if (_size < divider * divider * divider * divider * divider &&
_size % divider == 0) {
num r = _size / divider / divider / divider / divider;
return '${r.toStringAsFixed(0)} TB';
}
if (_size < divider * divider * divider * divider * divider) {
num r = _size / divider / divider / divider / divider;
return '${r.toStringAsFixed(round)} TB';
}
if (_size < divider * divider * divider * divider * divider * divider &&
_size % divider == 0) {
num r = _size / divider / divider / divider / divider / divider;
return '${r.toStringAsFixed(0)} PB';
} else {
num r = _size / divider / divider / divider / divider / divider;
return '${r.toStringAsFixed(round)} PB';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment