NumberFormater.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Numerics;
  6. using System.Text.RegularExpressions;
  7. namespace Masuit.Tools.Strings
  8. {
  9. /// <summary>
  10. /// 数制格式化器
  11. /// </summary>
  12. public class NumberFormater
  13. {
  14. /// <summary>
  15. /// 数制表示字符集
  16. /// </summary>
  17. private string Characters { get; set; }
  18. /// <summary>
  19. /// 进制长度
  20. /// </summary>
  21. public int Length => Characters.Length;
  22. /// <summary>
  23. /// 起始值偏移
  24. /// </summary>
  25. private readonly byte _offset;
  26. /// <summary>
  27. /// 数制格式化器
  28. /// </summary>
  29. public NumberFormater()
  30. {
  31. Characters = "0123456789";
  32. }
  33. /// <summary>
  34. /// 数制格式化器
  35. /// </summary>
  36. /// <param name="characters">符号集</param>
  37. /// <param name="offset">起始值偏移</param>
  38. public NumberFormater(string characters, byte offset = 0)
  39. {
  40. if (string.IsNullOrEmpty(characters))
  41. {
  42. throw new ArgumentException("符号集不能为空");
  43. }
  44. Characters = characters;
  45. _offset = offset;
  46. }
  47. /// <summary>
  48. /// 数制格式化器
  49. /// </summary>
  50. /// <param name="base">进制</param>
  51. /// <param name="offset">起始值偏移</param>
  52. public NumberFormater(byte @base, byte offset = 0)
  53. {
  54. if (@base < 2)
  55. {
  56. @base = 2;
  57. }
  58. if (@base > 64)
  59. {
  60. throw new ArgumentException("默认进制最大支持64进制");
  61. }
  62. Characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/".Substring(0, @base);
  63. if (offset >= @base)
  64. {
  65. throw new ArgumentException("偏移量不能超过进制基数" + @base);
  66. }
  67. _offset = offset;
  68. }
  69. /// <summary>
  70. /// 数字转换为指定的进制形式字符串
  71. /// </summary>
  72. /// <param name="number"></param>
  73. /// <returns></returns>
  74. public string ToString(long number)
  75. {
  76. int start = 0;
  77. int resultOffset = 0;
  78. if (_offset > 0)
  79. {
  80. start = 1;
  81. resultOffset = _offset - 1;
  82. }
  83. number = number - resultOffset;
  84. List<string> result = new List<string>();
  85. long t = Math.Abs(number);
  86. while (t != 0)
  87. {
  88. var mod = t % Length;
  89. t = Math.Abs(t / Length);
  90. var character = Characters[Convert.ToInt32(mod) - start].ToString();
  91. result.Insert(0, character);
  92. }
  93. if (number < 0)
  94. {
  95. result.Insert(0, "-");
  96. }
  97. return string.Join("", result);
  98. }
  99. /// <summary>
  100. /// 数字转换为指定的进制形式字符串
  101. /// </summary>
  102. /// <param name="number"></param>
  103. /// <returns></returns>
  104. public string ToString(BigInteger number)
  105. {
  106. int start = 0;
  107. int resultOffset = 0;
  108. if (_offset > 0)
  109. {
  110. start = 1;
  111. resultOffset = _offset - 1;
  112. }
  113. number = number - resultOffset;
  114. List<string> result = new List<string>();
  115. if (number < 0)
  116. {
  117. number = -number;
  118. result.Add("0");
  119. }
  120. BigInteger t = number;
  121. while (t != 0)
  122. {
  123. var mod = t % Length;
  124. t = BigInteger.Abs(BigInteger.Divide(t, Length));
  125. var character = Characters[(int)mod - start].ToString();
  126. result.Insert(0, character);
  127. }
  128. return string.Join("", result);
  129. }
  130. /// <summary>
  131. /// 指定字符串转换为指定进制的数字形式
  132. /// </summary>
  133. /// <param name="str"></param>
  134. /// <returns></returns>
  135. public long FromString(string str)
  136. {
  137. byte start = 0;
  138. int resultOffset = 0;
  139. if (_offset > 0)
  140. {
  141. start = 1;
  142. resultOffset = _offset - 1;
  143. }
  144. int j = 0;
  145. var chars = str.ToCharArray();
  146. Array.Reverse(chars);
  147. return new string(chars).Where(Characters.Contains).Sum(ch => (Characters.IndexOf(ch) + start) * (long)Math.Pow(Length, j++)) + resultOffset;
  148. }
  149. /// <summary>
  150. /// 指定字符串转换为指定进制的大数形式
  151. /// </summary>
  152. /// <param name="str"></param>
  153. /// <returns></returns>
  154. public BigInteger FromStringBig(string str)
  155. {
  156. byte start = 0;
  157. int resultOffset = 0;
  158. if (_offset > 0)
  159. {
  160. start = 1;
  161. resultOffset = _offset - 1;
  162. }
  163. int j = 0;
  164. var charArray = str.ToCharArray();
  165. Array.Reverse(charArray);
  166. var chars = charArray.Where(Characters.Contains);
  167. return chars.Aggregate(BigInteger.Zero, (current, c) => current + (Characters.IndexOf(c) + start) * BigInteger.Pow(Length, j++)) + resultOffset;
  168. }
  169. /// <summary>Returns a string that represents the current object.</summary>
  170. /// <returns>A string that represents the current object.</returns>
  171. public override string ToString()
  172. {
  173. return Length + "进制模式,进制符:" + Characters;
  174. }
  175. // 转换数字
  176. private static char ToNum(char x)
  177. {
  178. string strChnNames = "零一二三四五六七八九";
  179. string strNumNames = "0123456789";
  180. return strChnNames[strNumNames.IndexOf(x)];
  181. }
  182. // 转换万以下整数
  183. private static string ChangeInt(string x)
  184. {
  185. string[] strArrayLevelNames = { "", "十", "百", "千" };
  186. string ret = "";
  187. int i;
  188. for (i = x.Length - 1; i >= 0; i--)
  189. {
  190. if (x[i] == '0')
  191. {
  192. ret = ToNum(x[i]) + ret;
  193. }
  194. else
  195. {
  196. ret = ToNum(x[i]) + strArrayLevelNames[x.Length - 1 - i] + ret;
  197. }
  198. }
  199. while ((i = ret.IndexOf("零零", StringComparison.Ordinal)) != -1)
  200. {
  201. ret = ret.Remove(i, 1);
  202. }
  203. if (ret[ret.Length - 1] == '零' && ret.Length > 1)
  204. {
  205. ret = ret.Remove(ret.Length - 1, 1);
  206. }
  207. if (ret.Length >= 2 && ret.Substring(0, 2) == "一十")
  208. {
  209. ret = ret.Remove(0, 1);
  210. }
  211. return ret;
  212. }
  213. // 转换整数
  214. private static string ToInt(string x)
  215. {
  216. int len = x.Length;
  217. string result;
  218. string temp;
  219. if (len <= 4)
  220. {
  221. result = ChangeInt(x);
  222. }
  223. else if (len <= 8)
  224. {
  225. result = ChangeInt(x.Substring(0, len - 4)) + "万";
  226. temp = ChangeInt(x.Substring(len - 4, 4));
  227. if (temp.IndexOf("千", StringComparison.Ordinal) == -1 && !string.IsNullOrEmpty(temp))
  228. {
  229. result += "零" + temp;
  230. }
  231. else
  232. {
  233. result += temp;
  234. }
  235. }
  236. else
  237. {
  238. result = ChangeInt(x.Substring(0, len - 8)) + "亿";
  239. temp = ChangeInt(x.Substring(len - 8, 4));
  240. if (temp.IndexOf("千", StringComparison.Ordinal) == -1 && !string.IsNullOrEmpty(temp))
  241. {
  242. result += "零" + temp;
  243. }
  244. else
  245. {
  246. result += temp;
  247. }
  248. result += "万";
  249. temp = ChangeInt(x.Substring(len - 4, 4));
  250. if (temp.IndexOf("千", StringComparison.Ordinal) == -1 && !string.IsNullOrEmpty(temp))
  251. {
  252. result += "零" + temp;
  253. }
  254. else
  255. {
  256. result += temp;
  257. }
  258. }
  259. int i;
  260. if ((i = result.IndexOf("零万", StringComparison.Ordinal)) != -1)
  261. {
  262. result = result.Remove(i + 1, 1);
  263. }
  264. while ((i = result.IndexOf("零零", StringComparison.Ordinal)) != -1)
  265. {
  266. result = result.Remove(i, 1);
  267. }
  268. if (result[result.Length - 1] == '零' && result.Length > 1)
  269. {
  270. result = result.Remove(result.Length - 1, 1);
  271. }
  272. return result;
  273. }
  274. /// <summary>
  275. /// 转换为中文数字格式
  276. /// </summary>
  277. /// <param name="num">123.45</param>
  278. /// <returns></returns>
  279. public static string ToChineseNumber(IConvertible num)
  280. {
  281. var x = num.ToString(CultureInfo.CurrentCulture);
  282. if (x.Length == 0)
  283. {
  284. return "";
  285. }
  286. string result = "";
  287. if (x[0] == '-')
  288. {
  289. result = "负";
  290. x = x.Remove(0, 1);
  291. }
  292. if (x[0].ToString() == ".")
  293. {
  294. x = "0" + x;
  295. }
  296. if (x[x.Length - 1].ToString() == ".")
  297. {
  298. x = x.Remove(x.Length - 1, 1);
  299. }
  300. if (x.IndexOf(".") > -1)
  301. {
  302. result += ToInt(x.Substring(0, x.IndexOf("."))) + "点" + x.Substring(x.IndexOf(".") + 1).Aggregate("", (current, t) => current + ToNum(t));
  303. }
  304. else
  305. {
  306. result += ToInt(x);
  307. }
  308. return result;
  309. }
  310. /// <summary>
  311. /// 数字转中文金额大写
  312. /// </summary>
  313. /// <param name="number">22.22</param>
  314. public static string ToChineseMoney(IConvertible number)
  315. {
  316. /*
  317. #:用数字替换字符位置,如果数字小于对应值的位数,则在左侧填充零。
  318. L:将整数转换为一个字符串,并将其转换为小写字母形式。
  319. E:将数字格式化为科学计数法,并使用大写字母 E 表示指数。
  320. D:将数字格式化为整数,并使用逗号分隔数字组。
  321. C:将数字转换为货币格式,并使用本地货币符号。
  322. K:将数字格式化为千位分隔数字,使用 K 表示千。
  323. J:将数字格式化为十位分隔数字,使用 J 表示十。
  324. I:将数字格式化为百位分隔数字,使用 I 表示百。
  325. H:将数字格式化为千万位分隔数字,使用 H 表示千万。
  326. G:将数字格式化为一般格式,根据数字的大小和精度选择固定点或科学计数法表示。
  327. F:将数字格式化为固定点格式,并指定小数位数。
  328. .0:指定小数点后的位数为零。
  329. B:将数字转换为二进制格式。
  330. A:将数字转换为 ASCII 字符。
  331. */
  332. var s = number.ConvertTo<decimal>().ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");
  333. /*
  334. * ((?<=-|^)[^1-9]*): 匹配负号(如果存在),并且匹配在小数点前面的所有非数字字符。
  335. * ((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L\.]|$)))): 匹配小数点前面的数字。首先匹配一个零,然后匹配任意数量的零到 E 的字母。接下来,它匹配非零数字,或者如果遇到了小数点、字母 F-L 或者字符串的结尾,它会匹配上一个“-z”(即前面匹配的零)。
  336. * ((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[\  .]|$)))): 匹配小数点后面的数字。首先匹配字母 F-L,并将其存储在组“b”中。接着,它匹配一个零,并将其存储在组“z”中。然后,它匹配任意数量的零到字母 L 的字母。最后,匹配非零数字,或者如果遇到了小数点或字符串的结尾,它会匹配上一个“-z”(即前面匹配的零)。
  337. */
  338. var d = Regex.Replace(s, @"((?<=-|^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L\.]|$))))|((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[\  .]|$))))", "${b}${z}");
  339. /*
  340. * 将其转换为对应的中文大写字符,例如将'1'转换为'壹',将'2'转换为'贰',以此类推。Lambda表达式中使用了一个映射表,通过字符的ASCII码值来查找对应的中文字符。
  341. */
  342. return Regex.Replace(d, ".", m => "负元空零壹贰叁肆伍陆柒捌玖空空空空空空空分角拾佰仟萬億兆京垓秭穰"[m.Value[0] - '-'].ToString());
  343. }
  344. }
  345. }