大写金额字符串生成 C#实现
2014-03-29 22:00
267 查看
思路:
中文对金额的描述以四位为一组,
只考虑一万亿以内的数字则每组内以千、百、十和[亿\万\元]区分各位
连续的零按一个处理,组内最低位的零可略去
无角无分说整,有角无分只说角,无角有分说零X分,有角有分...
代码:
--------------------------------------
这个代码只适合一亿以内的金额,但相信以满足绝大多数情况
中文对金额的描述以四位为一组,
只考虑一万亿以内的数字则每组内以千、百、十和[亿\万\元]区分各位
连续的零按一个处理,组内最低位的零可略去
无角无分说整,有角无分只说角,无角有分说零X分,有角有分...
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MorrisSpace { /// <summary> /// 中文金额字符串辅助类。Helper for Amount string in Chinese /// </summary> public class AmountStringHelper { static private readonly char[] units = { '分', '角', '拾', '佰', '仟', '圆', '万', '亿', '整' }; // 0 1 2 3 4 5 6 7 8 static private readonly char[] numbers = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; /// <summary> /// 数字金额转大写金额 /// </summary> /// <param name="num">金额数字</param> /// <returns>大写金额字符串</returns> public static string GetAmountInWords(double num) { double amount = Math.Round(num, 2); long integ = (int)amount; double fract = Math.Round(amount - integ, 2); if (integ.ToString().Length > 12) { return null; } string result = ""; if (fract - 0.0 != 0) { string tempstr = fract.ToString(); if (tempstr.Length == 3) { result += numbers[(int)(fract * 10)]; result += units[1]; } else { int frist = (int)(fract * 10); int second = (int)(fract * 100 - frist * 10); if (frist != 0) { result += numbers[frist]; result += units[1]; result += numbers[second]; result += units[0]; } else { result += numbers[0]; result += numbers[second]; result += units[0]; } } } else { result += units[8]; } for (int temp = (int)(integ % 10000), secnum = 1; temp != 0; temp = (int)(integ % 10000), secnum++) { result = FourBitTrans(temp) + units[secnum + 4] + result; integ /= 10000; if (integ != 0 && temp < 1000) { result = numbers[0] + result; } } return result; } /// <summary> /// 进行四位数字转换的辅助函数 /// </summary> /// <param name="num">四位以下数字</param> /// <returns>大写金额四位节</returns> public static string FourBitTrans(int num) { string tempstr = num.ToString(); if (tempstr.Length > 4) { return null; } string result = string.Empty; int i = tempstr.Length; int j = 0; bool zeromark = true; while (--i >= 0) { j++; if (tempstr[i] == '0') { if (zeromark == true) { continue; } zeromark = true; result = numbers[0] + result; continue; } zeromark = false; if (j > 1) { result = units[j] + result; } int temp = tempstr[i] - '0'; result = numbers[temp] + result; } return result; } } }
--------------------------------------
这个代码只适合一亿以内的金额,但相信以满足绝大多数情况
相关文章推荐
- C#-控制台-多彩控制台,sleep函数,背景函数....---ShinePans
- C#-猜数游戏-控制台(随机数)---ShinePans
- C#遍历(foreach,...)---ShinePans
- C#中打开OpenFileDialog会改变默认路径的问题
- c#完成的数制转换器---ShinePans
- C#条件语句、循环语句
- c#中WebBrowser控件
- c#数据类型和表达式
- C#变量、常量
- c# 类型转换
- c# 类型转换
- C#中绘制文字两套代码
- C#——装箱(boxing)和拆箱(unboxing)
- C# 时间函数
- C#线程池的代码
- C#中的split函数用法详解
- C# yield
- C#类型和变量——引用类型
- C#(三)-听说委托“不简单”
- OpenCV c#版 CodeBook