将数字转化为中文

来源:互联网 发布:淘宝的虎扑伙伴怎么样 编辑:程序博客网 时间:2024/06/11 05:14

其实很简单,根本用不着写得很长很长。每4位分开,数字后面加上十百千万等,另外再处理掉多余的零就可以了。

 


  1. static string GetChineseString(double number)  
  2. {  
  3.     string[] cStr = new string[] { "零""一""二""三""四""五""六""七""八""九""""十""百""千" };  
  4.     string[] unitStr = new string[] { """万""亿""万""兆"};  
  5.     long intPart = (long)number;  
  6.     string result = string.Empty;  
  7.     for (int i = 0; i < intPart.ToString().Length; i++)  
  8.     {  
  9.         int temp = (int)((long)(intPart / (long)Math.Pow(10, i)) % 10);  
  10.         if (i % 4 == 0) result = unitStr[(int)i / 4] + result;  
  11.         result = cStr[temp] + cStr[10 + i % 4] + result;  
  12.     }  
  13.     result = Regex.Replace(result, "(零[十百千])+""零");  
  14.     result = Regex.Replace(result, "零{2,}""零");  
  15.     result = Regex.Replace(result, "零([万亿兆])""$1");  
  16.     if(result.Length>1)result = result.TrimEnd('零');  
  17.     if (number - intPart == 0) return result;  
  18.     string decimalPart = number.ToString().Split('.')[1];  
  19.     result += "点";  
  20.     for (int j = 0; j < decimalPart.Length; j++)  
  21.     {  
  22.         int temp = int.Parse(decimalPart[j].ToString());  
  23.         result += cStr[temp];  
  24.     }  
  25.     return result;  
  26. }  
  27.   
  28. static string GetChineseString(long number)  
  29. {  
  30.     string[] cStr =new string[] {"零","一","二","三","四","五","六","七","八","九","","十","百","千"};  
  31.     string[] unitStr = new string[] { """万""亿""万""兆" };  
  32.     string result = string.Empty;  
  33.     for (int i = 0; i < number.ToString().Length; i++)  
  34.     {  
  35.         int temp = (int)((long)(number / (long)Math.Pow(10, i)) % 10);//获取第i位的数字  
  36.         if (i % 4 == 0) result = unitStr[(int)i / 4] + result;//检查是否需要加上万或亿等  
  37.         result = cStr[temp] + cStr[10 + i % 4] + result;  
  38.     }  
  39.     result = Regex.Replace(result, "(零[十百千])+""零");  
  40.     result = Regex.Replace(result, "零{2,}""零");  
  41.     result = Regex.Replace(result, "零([万亿兆])""$1");  
  42.     if(result.Length>1)result = result.TrimEnd('零');  
  43.     return result;  

原创粉丝点击