StringUtils.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using FL.Network;
  2. using System;
  3. namespace FL
  4. {
  5. public static class StringUtils
  6. {
  7. /// <summary>
  8. /// 毫秒转指定格式的时间字符串
  9. /// </summary>
  10. /// <param name="milliseconds"></param>
  11. /// <param name="format">字符串格式, 例: @"mm\:ss"</param>
  12. /// <returns></returns>
  13. public static string ToTimeString(this long milliseconds, string format)
  14. {
  15. var timeData = TimeSpan.FromMilliseconds(milliseconds);
  16. return timeData.ToString(format);
  17. }
  18. private const string MILLION = "M";
  19. private const string THOUSAND = "K";
  20. /// <summary>
  21. /// 货币、战力数字转字符串
  22. /// >=百万,以M结尾
  23. /// >=万,以K结尾
  24. /// </summary>
  25. /// <param name="number"></param>
  26. /// <param name="decimals">保留小数点位数</param>
  27. /// <returns></returns>
  28. public static string FormatNumber(this long number, int decimals = 1)
  29. {
  30. const int million = 1000000;
  31. const int thousand = 1000;
  32. var format = $"N{decimals}";//$"{{0:N{decimals}}}";
  33. if (number >= million)
  34. {
  35. return ((double)number / million).ToString(format) + MILLION;
  36. }
  37. if (number >= thousand * 10)
  38. {
  39. return ((double)number / thousand).ToString(format) + THOUSAND;
  40. }
  41. return number.ToString();
  42. }
  43. /// <summary>
  44. /// 时间戳转换成 xxxx-xx-xx xx:xx格式
  45. /// </summary>
  46. /// <param name="milliseconds"></param>
  47. /// <returns></returns>
  48. public static string ToTimeYMDHM(this long milliseconds)
  49. {
  50. DateTimeOffset dateTime = DateTimeOffset.FromUnixTimeSeconds(milliseconds);
  51. string yearMonthDay = dateTime.ToString("yyyy-MM-dd hh:mm");
  52. return yearMonthDay;
  53. }
  54. /// <summary>
  55. /// 数据库万分比字段转真实值以显示百分比显示(最多保留小数点后2位,小数部分为零时不显示)
  56. /// </summary>
  57. /// <param name="val"></param>
  58. /// <returns></returns>
  59. public static string ToRealFloatPercentage(this int val)
  60. {
  61. return val > 0 ? (val * 0.0001f).ToString("G2") + "%" : "0%";
  62. }
  63. /// <summary>
  64. /// 数据库万分比字段转真实值以显示百分比显示(最多保留小数点后2位,小数部分为零时不显示)
  65. /// </summary>
  66. /// <param name="val"></param>
  67. /// <returns></returns>
  68. public static string ToRealDoublePercentage(this long val)
  69. {
  70. return val > 0 ? (val * 0.0001f).ToString("G2") + "%" : "0%";
  71. }
  72. }
  73. }