C# 金额转大写 小数点后两位

  打印财务方面的内容时,时常需要将金额转换为大写。以下是金额转大写源码

 1         public static string NumtoChinese(decimal s)
 2         {
 3             s = Math.Round(s, 2);//四舍五入到两位小数,即分
 4             string[] n = { "", "", "", "", "", "", "", "", "", "" };
 5             //数字转大写
 6             string[] d = { "", "", "", "", "", "", "", "", "", "", "", "亿" };
 7             //不同位置的数字要加单位
 8             List<string> needReplace = new List<string> { "零拾", "零佰", "零仟", "零万", "零亿", "亿万", "零元", "零零", "零角", "零分" };
 9             List<string> afterReplace = new List<string> { "", "", "", "", "亿", "亿", "", "", "", "" };//特殊情况用replace剔除
10             string e = s % 1 == 0 ? "" : "";//金额是整数要加一个“整”结尾
11             string re = "";
12             Int64 a = (Int64)(s * 100);
13             int k = 1;
14             while (a != 0)
15             {//初步转换为大写+单位
16                 re = n[a % 10] + d[k] + re;
17                 a = a / 10;
18                 k = k < 11 ? k + 1 : 4;
19             }
20             string need = needReplace.Where(tb => re.Contains(tb)).FirstOrDefault<string>();
21             while (need != null)
22             {
23                 int i = needReplace.IndexOf(need);
24                 re = re.Replace(needReplace[i], afterReplace[i]);
25                 need = needReplace.Where(tb => re.Contains(tb)).FirstOrDefault<string>();
26             }//循环排除特殊情况
27             re = re == "" ? "" : re + e;
28             return re;
29         }

 

posted @ 2019-03-27 22:51  陈彦斌  阅读(755)  评论(0)    收藏  举报