data_util.dart 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import 'dart:math';
  2. final storageUnits = ["bytes", "KB", "MB", "GB"];
  3. String convertBytesToReadableFormat(int bytes) {
  4. int storageUnitIndex = 0;
  5. while (bytes >= 1024 && storageUnitIndex < storageUnits.length - 1) {
  6. storageUnitIndex++;
  7. bytes = (bytes / 1024).round();
  8. }
  9. return bytes.toString() + " " + storageUnits[storageUnitIndex];
  10. }
  11. String formatBytes(int bytes, [int decimals = 2]) {
  12. if (bytes == 0) return '0 bytes';
  13. const k = 1024;
  14. final int dm = decimals < 0 ? 0 : decimals;
  15. final int i = (log(bytes) / log(k)).floor();
  16. return ((bytes / pow(k, i)).toStringAsFixed(dm)) + ' ' + storageUnits[i];
  17. }
  18. //shows decimals only if less than 10GB & omits decimal if decimal is 0
  19. num convertBytesToGBs(int bytes) {
  20. const tenGBinBytes = 10737418240;
  21. int precision = 0;
  22. if (bytes < tenGBinBytes) {
  23. precision = 1;
  24. }
  25. final bytesInGB =
  26. num.parse((bytes / (pow(1024, 3))).toStringAsPrecision(precision));
  27. return bytesInGB;
  28. }
  29. int convertBytesToMBs(int bytes) {
  30. return (bytes / pow(1024, 2)).round();
  31. }