SiHelper.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Veldrid.Common.Tools
  5. {
  6. internal static class SiHelper
  7. {
  8. private static string SICollection = "yzafpnμmDkMGTPEZY";
  9. public static string ValueChangeToSI(double value, out string siUnit, out string numberstring, int decimals = 1, string unit = "", bool invalid = false)
  10. {
  11. string formatstring = "#0";
  12. if (!invalid)
  13. {
  14. if (decimals > 0)
  15. {
  16. formatstring += ".";
  17. for (int i = 0; i < decimals; i++) formatstring += "#";
  18. }
  19. }
  20. else
  21. {
  22. formatstring = "N" + decimals;
  23. }
  24. siUnit = unit;
  25. if (double.IsNaN(value))
  26. {
  27. numberstring = "NaN";
  28. return "NaN";
  29. }
  30. if (value == 0)
  31. {
  32. numberstring = value.ToString(formatstring);
  33. return numberstring + unit;
  34. }
  35. if (Math.Abs(value) < 1E-24)
  36. {
  37. numberstring = Math.Round((decimal)0f, decimals) + "";
  38. return Math.Round((decimal)0f, decimals) + unit;
  39. }
  40. string SI = SICollection;
  41. double d = Math.Log(Math.Abs(value), 1000);
  42. decimal number = Math.Round((decimal)(value / Math.Pow(1000, Math.Floor(d))), decimals);
  43. d += 8;
  44. if (d > 16)
  45. {
  46. numberstring = "NaN";
  47. siUnit = "";
  48. return "";
  49. }
  50. string s = SI.Substring((int)d, 1);
  51. if (s == "D") s = "";
  52. siUnit = s + unit;
  53. numberstring = number.ToString(formatstring);
  54. return numberstring + siUnit;
  55. }
  56. }
  57. }