数值转大写人民币
类似的小功能网上有很多写法,但关键在于思路。思路决定了代码的精炼,决定了效能。
1)将12345.6789转为“壹万贰仟叁佰肆拾伍元陆角捌分”
逻辑:
第一步)四舍五入取2位小数,然后去掉小数点。
第二步)循环每个字符,把数字转为对应的大写汉字,并在其后加入单位标识{x}
第三步)把标识{x}替换为对应的单位
public string getMoneyUpper(double money) { string n = money.ToString("#0.00").Replace(".", ""); string MoneyUpper = ""; int l = n.Length; for (int i = 0; i < n.Length; i++) { switch (n[i].ToString()) { case "0": MoneyUpper += "零"; break; case "1": MoneyUpper += "壹"; break; case "2": MoneyUpper += "贰"; break; case "3": MoneyUpper += "叁"; break; case "4": MoneyUpper += "肆"; break; case "5": MoneyUpper += "伍"; break; case "6": MoneyUpper += "陆"; break; case "7": MoneyUpper += "柒"; break; case "8": MoneyUpper += "捌"; break; case "9": MoneyUpper += "玖"; break; default: break; } MoneyUpper += "{" + l + "}"; l--; }
MoneyUpper = MoneyUpper.Replace("{1}", "分");
MoneyUpper = MoneyUpper.Replace("{2}", "角");
MoneyUpper = MoneyUpper.Replace("{3}", "元");
MoneyUpper = MoneyUpper.Replace("{4}", "拾");
MoneyUpper = MoneyUpper.Replace("{5}", "佰");
MoneyUpper = MoneyUpper.Replace("{6}", "仟");
MoneyUpper = MoneyUpper.Replace("{7}", "萬");
MoneyUpper = MoneyUpper.Replace("{8}", "拾");
return MoneyUpper; }
2)找到12345.6789的第1个位置(从右向左,分开始)的大写汉字
public static string getCapsMoney(double money,int index) { string n = money.ToString("#0.00").Replace(".", ""); if (index < n.Length) { switch (n[n.Length - 1 - index].ToString()) { case "0": return "零"; case "1": return "壹"; case "2": return "贰"; case "3": return "叁"; case "4": return "肆"; case "5": return "伍"; case "6": return "陆"; case "7": return "柒"; case "8": return "捌"; case "9": return "玖"; default: return "/"; } } else return "/"; }