data_util.dart 1.2 KB

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