日期:2010-12-24  浏览次数:20460 次

  最近由于项目的原因,需要写一个货币数字转换中文的算法,先在网了找了一下,结果发现无一列外都是用(Replace)替换的方式来实现的,所以想写个另外的算法;因为本人是学数学出身的,所以用纯数学的方法实现。

  注意:本文中的算法支持小于1023 (也就是9999亿兆)货币数字转化。

  货币中文说明: 在说明代码之前,首先让我们回顾一下货币的读法。

  10020002.23  读为 壹仟零贰万零贰元贰角叁分
  1020         读为 壹仟零贰拾元整。
  100000       读为 拾万元整
  0.13         读为 壹角叁分

 

  代码:

测试工程
  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();
}

测试结果如下:

货币转化类(NumCast类)功能介绍

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 = "整";

 

2:数字合法性验证,采用正则表达式验证
 /// <summary>
/// 正则表达验证数字是否合法
/// </summary>
/// <param name="Num"></param>
/// <returns></returns>
public bool IsValidated<T>(T Num)
{
Regex reg = new Regex(@"^(([0])|([1-9]\d{0,23}))(\.\d{1,2})?$");
if (reg.IsMatch(Num.ToString()))
{
return true;

}
return false;
}

3: 获取数位 例如 1000的数位为 NumLevel.Thousand

/// <summary>
/// 获取数字的数位 使用log
/// </summary>
/// <param name="Num"></param>
/// <returns></returns>
private NumLevel GetNumLevel(double Num)
{
double numLevelLength;
NumLevel NLvl = new NumLevel();
if (Num > 0)
{
numLevelLength = Math.Floor(Math.Log10(Num));
for (int i = NumLevelExponent.Length - 1; i >= 0; i--)
{
if (numLevelLength >= NumLevelExponent[i])
{
NLvl = (NumLevel)i;
break;
}
}
}
else
{
NLvl = NumLevel.Yuan;
}
return NLvl;

}

4:判断数字之间是否有跳位,也就是中文中间是否要加零,例如1020 就应该加零。
 /// <summary>
/// 是否跳位
/// </summary>
/// <returns></returns>
private bool IsDumpLevel(double Num)
{
 if (Num > 0)
{
NumLevel? currentLevel = GetNumLevel(Num);
NumLevel? nextLevel = null;
int numExponent = this.NumLevelExponent[(int)currentLevel];

double postfixNun = Math.Round(Num % (Math.Pow(10, numExponent)),2);
if(postfixNun> 0)
nextLevel = GetNumLevel(postfixNun);
if (currentLevel != null && nextLevel != null)
{
if (currentLevel > nextLevel + 1)
{
return true;
}
}
}
return false;

}

5 把长数字分割为两个较小的数字数组,例如把9999亿兆,分割为9999亿和0兆,

因为计算机不支持过长的数字。
 /// <summary>
/// 是否大于兆,如果大于就把字符串分为两部分,
/// 一部分是兆以前的数字
/// 另一部分是兆以后的数字
/// &l