HumanReadHelper.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. namespace FNZCM.Shared.Helpers
  2. {
  3. public static class HumanReadHelper
  4. {
  5. public static string NullOrEmptyEscape(this string me, string escape) => string.IsNullOrWhiteSpace(me) ? escape : me;
  6. public static string SecondToDur(this int sec) => ((int?)sec).SecondToDur();
  7. public static string SecondToDur(this int? sec)
  8. {
  9. if (sec.HasValue == false) return string.Empty;
  10. var ts = TimeSpan.FromSeconds(sec.Value);
  11. return ts.Hours > 0
  12. ? $"{Math.Floor(ts.TotalHours):00}:{ts.Minutes:00}:{ts.Seconds:00}"
  13. : $"{Math.Floor(ts.TotalMinutes):00}:{ts.Seconds:00}";
  14. }
  15. public static string BytesToFileSize(this long length) => ((long?)length).BytesToFileSize();
  16. public static string BytesToFileSize(this long? length)
  17. {
  18. if (length.HasValue == false) return string.Empty;
  19. string[] sizes = { "B", "KB", "MB", "GB", "TB" };
  20. double len = length.Value;
  21. int order = 0;
  22. while (len >= 1024 && order < sizes.Length - 1)
  23. {
  24. order++;
  25. len = len / 1024;
  26. }
  27. // Adjust the format string to your preferences. For example "{0:0.#}{1}" would
  28. // show a single decimal place, and no space.
  29. string result = $"{len:000.00}{sizes[order]}";
  30. return result;
  31. }
  32. }
  33. }