金额转大写

虽然网上这个一搜一大把,今天看到一个帖子有人自己写了,分享出来,让大家帮找错。自己一时兴起,正好有空,就练练手写了一个,速度应该是比较快的。不废话了。贴代码

public static string GetChineseNum(decimal value) { string chinese = "零壹贰叁肆伍陆柒捌玖"; string unit = "元十百千万十百千亿十百千兆十百千"; string unit2 = "角分"; StringBuilder builder = new StringBuilder(); int u = 1; int i = 0; //整数 while (value >= u) { int n = (int)value / u % 10; u *= 10; if (n == 0) { i++; continue; } builder.Insert(0, unit[i++]); builder.Insert(0, chinese[n]); } if (builder[builder.Length - 1] != '元') { builder.Append("元"); } //小数 if ((int)value != value) { int value2 = (int)((value - (int)value) * 100); int n = value2 / 10 % 10; builder.Append(chinese[n]); builder.Append(unit2[0]); n = value2 % 10; builder.Append(chinese[n]); builder.Append(unit2[1]); } else { builder.Append("整"); } return builder.ToString(); }

如果折合成时间,我居然算是1分钟只写了2行,囧。

 

-----------------------------------------------------

 

根据评论1,考虑超过1万的情况,我也不确定是否这次就百分百对,原来的版本依然保留。贴新的如下。

 

public static string GetChineseNum(decimal value) { string chinese = "零壹贰叁肆伍陆柒捌玖"; string unit = "元十百千万十百千亿十百千兆十百千"; string unit2 = "角分"; StringBuilder builder = new StringBuilder(); long u = 1; int i = 0; //整数 while (value >= u) { int n = (int)((long)value / u % 10); u *= 10; if (n == 0) { i++; continue; } if (i > 1 && i < 4) { builder.Insert(0, "元"); } else if (i > 4 && i < 8) { builder.Insert(0, "万"); } else if (i > 8) { builder.Insert(0, "亿"); } builder.Insert(0, unit[i++]); builder.Insert(0, chinese[n]); } //小数 if ((long)value != value) { long value2 = (long)((value - (long)value) * 100); int n = (int)(value2 / 10 % 10); builder.Append(chinese[n]); builder.Append(unit2[0]); n = (int)(value2 % 10); builder.Append(chinese[n]); builder.Append(unit2[1]); } else { builder.Append("整"); } return builder.ToString(); }

你可能感兴趣的:(金额转大写)