// 金额转大写 - 绿色工具箱 // C# 5.0 语法,零依赖。发票/合同用人民币大写转换 // 内置自测:多组标准样例逐条断言,防止算法错(教训:金额类算法必须双向验证) using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class MoneyUpperToolForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_BG = Color.White; private static readonly Color COL_PANEL = Color.FromArgb(245, 249, 246); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private TextBox txtInput; private TextBox txtOutput; private Button btnConvert; private Button btnCopy; private Button btnSelfTest; private Label lblStatus; private static readonly string[] DIGITS = new string[] { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" }; private static readonly string[] UNITS = new string[] { "", "拾", "佰", "仟" }; private static readonly string[] GROUPS = new string[] { "", "万", "亿", "万亿" }; public MoneyUpperToolForm() { InitUi(); } private void InitUi() { this.Text = "金额转大写 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 10f); this.BackColor = COL_BG; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(680, 380); this.MinimumSize = new Size(600, 340); int x = 24, y = 20; Label l0 = new Label(); l0.Text = "输入数字金额(支持 ¥ 前缀、千分位逗号、两位小数),转成发票/合同用的人民币大写"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 34; Label l1 = new Label(); l1.Text = "小写金额:"; l1.AutoSize = true; l1.Location = new Point(x, y + 5); this.Controls.Add(l1); txtInput = new TextBox(); txtInput.Location = new Point(x + 90, y); txtInput.Size = new Size(420, 28); txtInput.Font = new Font("Consolas", 12f); txtInput.TextChanged += new EventHandler(OnChange); this.Controls.Add(txtInput); btnConvert = new Button(); btnConvert.Text = "转换"; btnConvert.Location = new Point(x + 524, y - 1); btnConvert.Size = new Size(110, 30); btnConvert.BackColor = COL_GREEN; btnConvert.ForeColor = Color.White; btnConvert.FlatStyle = FlatStyle.Flat; btnConvert.FlatAppearance.BorderSize = 0; btnConvert.Click += new EventHandler(OnChange); this.Controls.Add(btnConvert); y += 48; Label l2 = new Label(); l2.Text = "人民币大写:"; l2.AutoSize = true; l2.Location = new Point(x, y + 8); this.Controls.Add(l2); txtOutput = new TextBox(); txtOutput.Location = new Point(x + 90, y); txtOutput.Size = new Size(544, 32); txtOutput.Font = new Font("Microsoft YaHei UI", 13f, FontStyle.Bold); txtOutput.ReadOnly = true; txtOutput.BackColor = COL_PANEL; this.Controls.Add(txtOutput); y += 46; btnCopy = new Button(); btnCopy.Text = "复制大写结果"; btnCopy.Location = new Point(x, y); btnCopy.Size = new Size(130, 32); btnCopy.FlatStyle = FlatStyle.Flat; btnCopy.FlatAppearance.BorderColor = COL_GREEN; btnCopy.ForeColor = Color.FromArgb(0, 110, 66); btnCopy.Click += new EventHandler(CopyClick); this.Controls.Add(btnCopy); btnSelfTest = new Button(); btnSelfTest.Text = "内置自测(20 组)"; btnSelfTest.Location = new Point(x + 144, y); btnSelfTest.Size = new Size(150, 32); btnSelfTest.FlatStyle = FlatStyle.Flat; btnSelfTest.FlatAppearance.BorderColor = COL_GREEN; btnSelfTest.ForeColor = Color.FromArgb(0, 110, 66); btnSelfTest.Click += new EventHandler(SelfTestClick); this.Controls.Add(btnSelfTest); y += 52; Label lh = new Label(); lh.Text = "转换规则(按中国人民银行报销票据规范):"; lh.AutoSize = true; lh.Location = new Point(x, y); lh.ForeColor = COL_GRAY; this.Controls.Add(lh); y += 24; string[] rules = new string[] { "· 阿拉伯数字中间连续有几个\"0\"时,中文大写只写一个\"零\"字(如 1005.03 → 壹仟零伍元零叁分)", "· 整数到元、无角分的,末尾加\"整\";有分的,不加\"整\"", "· 角位是 0 而分位不是 0 的,元后写\"零\"(如 1.05 → 壹元零伍分)", "· 支持到万亿;负数写作\"(负)\";超过两位小数按四舍五入到分" }; foreach (string s in rules) { Label lr = new Label(); lr.Text = s; lr.AutoSize = true; lr.Location = new Point(x, y); lr.ForeColor = COL_GRAY; this.Controls.Add(lr); y += 24; } lblStatus = new Label(); lblStatus.Text = ""; lblStatus.Location = new Point(x, this.ClientSize.Height - 30); lblStatus.AutoSize = true; this.Controls.Add(lblStatus); } private void OnChange(object sender, EventArgs e) { string parsed, err; decimal v; if (!ParseAmount(txtInput.Text, out v, out parsed, out err)) { txtOutput.Text = err.Length > 0 ? err : ""; return; } txtOutput.Text = ToUpperRmb(v); } private void CopyClick(object sender, EventArgs e) { if (txtOutput.Text.Length > 0 && lblStatus.Text != "输入有误") { Clipboard.SetText(txtOutput.Text); lblStatus.Text = "已复制。"; } } // 解析输入:支持 ¥、¥、逗号、负号、小数 private static bool ParseAmount(string raw, out decimal value, out string norm, out string err) { value = 0; norm = ""; err = ""; string s = raw.Trim().Replace("¥", "").Replace("¥", "").Replace(",", "").Replace(",", "").Replace(" ", ""); if (s.Length == 0) { err = ""; return false; } bool neg = false; if (s.StartsWith("-")) { neg = true; s = s.Substring(1); } decimal d; if (!decimal.TryParse(s, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out d)) { err = "输入有误"; return false; } if (neg) d = -d; d = Math.Round(d, 2, MidpointRounding.AwayFromZero); if (Math.Abs(d) >= 10000000000000000m) { err = "超出范围"; return false; } // 4组×4位 value = d; norm = d.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture); return true; } // 核心转换。整数部分按 4 位一组(个级/万级/亿级/万亿级) private static string ToUpperRmb(decimal v) { StringBuilder sb = new StringBuilder(); if (v < 0) sb.Append("(负)"); decimal abs = Math.Abs(v); long cents = (long)Math.Round(abs * 100, MidpointRounding.AwayFromZero); long yuan = cents / 100; int jiao = (int)((cents % 100) / 10); int fen = (int)(cents % 10); if (yuan > 0) { sb.Append(YuanToUpper(yuan)); sb.Append("元"); } if (jiao == 0 && fen == 0) { if (yuan > 0) sb.Append("整"); else sb.Append("零元整"); } else { if (yuan > 0 && jiao == 0 && fen > 0) sb.Append("零"); if (jiao > 0) sb.Append(DIGITS[jiao]).Append("角"); if (fen > 0) sb.Append(DIGITS[fen]).Append("分"); // 有角无分、有分无角都不加"整";"整"只出现在整数到元且无角分 } return sb.ToString(); } // 4 位一组转换,处理组内零与组间零 private static string YuanToUpper(long n) { if (n == 0) return ""; List groups = new List(); // 低到高 while (n > 0) { groups.Add((int)(n % 10000)); n /= 10000; } StringBuilder sb = new StringBuilder(); for (int g = groups.Count - 1; g >= 0; g--) { int val = groups[g]; if (val == 0) { // 整组为零:若后面(低位)还有非零组,补一个零 bool lowerNonZero = false; for (int k = g - 1; k >= 0; k--) if (groups[k] > 0) { lowerNonZero = true; break; } if (lowerNonZero && sb.Length > 0 && !sb.ToString().EndsWith("零")) sb.Append("零"); continue; } bool needZero = sb.Length > 0 && val < 1000 && !sb.ToString().EndsWith("零"); string gs = GroupToUpper(val); if (needZero) sb.Append("零"); sb.Append(gs); if (g > 0) sb.Append(GROUPS[g]); } return CleanZero(sb.ToString()); } private static string GroupToUpper(int v) { StringBuilder sb = new StringBuilder(); int qian = v / 1000, bai = (v % 1000) / 100, shi = (v % 100) / 10, ge = v % 10; bool zeroPending = false; if (qian > 0) sb.Append(DIGITS[qian]).Append(UNITS[3]); if (qian > 0 && bai == 0 && (shi > 0 || ge > 0)) zeroPending = true; if (bai > 0) { if (zeroPending) { sb.Append("零"); zeroPending = false; } sb.Append(DIGITS[bai]).Append(UNITS[2]); } else if (sb.Length > 0 && (shi > 0 || ge > 0)) zeroPending = true; if (shi > 0) { if (zeroPending) { sb.Append("零"); zeroPending = false; } // 100 一百?规范:10-19 拾X?金融票据:10 → 壹拾。所以 shi>0 直接写 sb.Append(DIGITS[shi]).Append(UNITS[1]); } else if (sb.Length > 0 && ge > 0) zeroPending = true; if (ge > 0) { if (zeroPending) sb.Append("零"); sb.Append(DIGITS[ge]); } return sb.ToString(); } private static string CleanZero(string s) { while (s.Contains("零零")) s = s.Replace("零零", "零"); if (s.EndsWith("零")) s = s.Substring(0, s.Length - 1); return s; } private void SelfTestClick(object sender, EventArgs e) { int pass, total; StringBuilder failDetail; RunSelfTest(out pass, out total, out failDetail); if (pass == total) MessageBox.Show("自测通过:" + pass + "/" + total + " 组全部一致。", "金额转大写 · 内置自测", MessageBoxButtons.OK, MessageBoxIcon.Information); else MessageBox.Show("自测未全过:" + pass + "/" + total + "。\n失败明细:\n" + failDetail.ToString(), "金额转大写 · 内置自测", MessageBoxButtons.OK, MessageBoxIcon.Warning); } // 自测核心(供 UI 按钮与命令行 --selftest 共用)。返回 0=全过 1=有失败 public static int RunSelfTest() { int pass, total; StringBuilder failDetail; RunSelfTest(out pass, out total, out failDetail); System.IO.File.WriteAllText("selftest-money.txt", "pass=" + pass + "/" + total + "\r\n" + failDetail.ToString(), Encoding.UTF8); return pass == total ? 0 : 1; } public static void RunSelfTest(out int pass, out int total, out StringBuilder failDetail) { // 标准样例(按人行规范与票据惯例整理),逐条断言 string[,] tests = new string[,] { { "0", "零元整" }, { "0.5", "伍角" }, { "0.05", "伍分" }, { "1", "壹元整" }, { "10", "壹拾元整" }, { "15.5", "壹拾伍元伍角" }, { "100", "壹佰元整" }, { "101", "壹佰零壹元整" }, { "110", "壹佰壹拾元整" }, { "1005.03", "壹仟零伍元零叁分" }, { "1234.56", "壹仟贰佰叁拾肆元伍角陆分" }, { "10000", "壹万元整" }, { "100010", "壹拾万零壹拾元整" }, { "1000001.5", "壹佰万零壹元伍角" }, { "12345678.90", "壹仟贰佰叁拾肆万伍仟陆佰柒拾捌元玖角" }, { "100000000", "壹亿元整" }, { "1000000000000", "壹万亿元整" }, { "-12.34", "(负)壹拾贰元叁角肆分" }, { "0.01", "壹分" }, { "1.1", "壹元壹角" } }; pass = 0; total = tests.GetLength(0); failDetail = new StringBuilder(); for (int i = 0; i < total; i++) { decimal v; string parsed, err; if (!ParseAmount(tests[i, 0], out v, out parsed, out err)) continue; string got = ToUpperRmb(v); bool ok = got == tests[i, 1]; if (ok) pass++; else failDetail.AppendLine(tests[i, 0] + " 期望「" + tests[i, 1] + "」实际「" + got + "」"); } } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(MoneyUpperToolForm.RunSelfTest()); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MoneyUpperToolForm()); } } }