ByteConvertUtils.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Y.Utils.DataUtils.UnitConvertUtils
  7. {
  8. public class ByteConvertTool
  9. {
  10. public static string Fmt(long size, int digits = 2)
  11. {
  12. string rs = "";
  13. if (size > 1024 * 1024 * 1024)
  14. {
  15. rs = Math.Round((double)size / 1024 / 1024 / 1024, digits) + " GB";
  16. }
  17. else if (size > 1024 * 1024)
  18. {
  19. rs = Math.Round((double)size / 1024 / 1024, digits) + " MB";
  20. }
  21. else if (size > 1024)
  22. {
  23. rs = Math.Round((double)size / 1024, digits) + " KB";
  24. }
  25. else
  26. {
  27. rs = size + " B";
  28. }
  29. return rs;
  30. }
  31. public static string Fmt(double size, int digits = 2)
  32. {
  33. string rs = "";
  34. if (size > 1024 * 1024 * 1024)
  35. {
  36. rs = Math.Round(size / 1024 / 1024 / 1024, digits) + " GB";
  37. }
  38. else if (size > 1024 * 1024)
  39. {
  40. rs = Math.Round(size / 1024 / 1024, digits) + " MB";
  41. }
  42. else if (size > 1024)
  43. {
  44. rs = Math.Round(size / 1024, digits) + " KB";
  45. }
  46. else
  47. {
  48. rs = size + " B";
  49. }
  50. return rs;
  51. }
  52. public static string Cvt(long size, string unit, int digits = 2)
  53. {
  54. double rs = 0;
  55. switch (unit)
  56. {
  57. case "B": rs = size; break;
  58. case "KB": rs = (double)size / 1024; break;
  59. case "MB": rs = (double)size / 1024 / 1024; break;
  60. case "GB": rs = (double)size / 1024 / 1024 / 1024; break;
  61. }
  62. return Math.Round(rs, digits).ToString();
  63. }
  64. public static string Cvt(double size, string unit, int digits = 2)
  65. {
  66. double rs = 0;
  67. switch (unit)
  68. {
  69. case "B": rs = size; break;
  70. case "KB": rs = size / 1024; break;
  71. case "MB": rs = size / 1024 / 1024; break;
  72. case "GB": rs = size / 1024 / 1024 / 1024; break;
  73. }
  74. return Math.Round(rs, digits).ToString();
  75. }
  76. }
  77. }