最近由于项目的原因,需要写一个货币数字转换中文的算法,先在网了找了一下,结果发现无一列外都是用(Replace)替换的方式来实现的,所以想写个另外的算法;因为本人是学数学出身的,所以用纯数学的方法实现。
测试工程
static void Main(string[] args)
{
Console.WriteLine("请输入金额");
string inputNum = Console.ReadLine();
while (inputNum != "exit")
{
//货币数字转化类
NumCast nc = new NumCast();
if (nc.IsValidated<string>(inputNum))
{
try
{
string chineseCharacter = nc.ConvertToChinese(inputNum);
Console.WriteLine(chineseCharacter);
}
catch (Exception er)
{
Console.WriteLine(er.Message);
}
}
else
{
Console.WriteLine("不合法的数字或格式");
}
Console.WriteLine("\n请输入金额");
inputNum = Console.ReadLine();
}
Console.ReadLine();
}
1 常量的规定
/// <summary>
/// 数位
/// </summary>
public enum NumLevel { Cent, Chiao, Yuan, Ten, Hundred, Thousand, TenThousand, hundredMillon, Trillion };
/// <summary>
/// 数位的指数
/// </summary>
private int[] NumLevelExponent = new int[] { -2, -1, 0, 1, 2, 3, 4, 8, 12 };
/// <summary>
/// 数位的中文字符
/// </summary>
private string[] NumLeverChineseSign = new string[] { "分", "角", "元", "拾", "佰", "仟", "万", "亿", "兆" };
/// <summary>
/// 大写字符
/// </summary>
private string[] NumChineseCharacter = new string[] {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
/// <summary>
/// 整(当没有 角分 时)
/// </summary>
private const string EndOfInt = "整";