前接上篇,阿拉伯数字转中文数字是蛮有意思的,最近又有新发现~现在更新一下以前的代码~
c#版的阿拉伯数字转中文大写,以及票据日期的写法
不废话,直接上代码,两个方法
阿拉伯数字转中文:
private static char[] CN_UPPER_NUM = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };
private static char[] CN_UNIT = { '亿', '拾', '佰', '仟', '万' };
public static string ArabicNumToCn(string num)
{
StringBuilder des = new StringBuilder("");
bool preZero = false;//前一位是否为0标志,起始前一位不为零
int length = num.Length;// 字符串长度
int hundredMillions = length / 8;// 加多个“亿”字符的数量
bool hasValue = true;
int index_4 = 0;// 取余4的值
int index_8 = 0;// 取余8的值
for (int i = 0; i < length; i++)
{
int n = length - 1 - i;// 从最高位开始扫描,字符串0位置为最高位位置((length-1)开始到0结束)
char cInt = num[i];// 当前字符
index_4 = n % 4;// 取余4 根据index_4的值接上 '拾', '佰', '仟'
index_8 = n % 8;// 取余8 根据index_8的值接上'亿', '万'
// 当前位的数字非零
if (cInt != '0')
{
// 是否接上零(前一位为0则加上0)
if (preZero)
{
des.Append(CN_UPPER_NUM[0]);
preZero = false;
}
des.Append(CN_UPPER_NUM[cInt - '0']);
// 根据index_4的值接上 '拾', '佰', '仟'
if (index_4 != 0)
{
des.Append(CN_UNIT[index_4]);
}
hasValue = true;
}
else
{
// 当前位为零则置preZero为true值
preZero = true;//(cInt == '0');
}
//如果万位之前有非零值接上'万'
if (index_8 == 4 && hasValue)
{
des.Append(CN_UNIT[index_8]);
}
//亿位的处理
if (index_8 == 0)
{
//超过9位数才处理,且亿位之前有非零值
if (i <= length - 9 && hasValue)
{
//累加接上'亿',不用累加就只去掉循环
for (int j = 0; j < hundredMillions; j++)
{
des.Append(CN_UNIT[0]);
}
}
hundredMillions--;// 将减少“亿”的累加次数
hasValue = false;
}
}
// 返回目标数组
return des.ToString();
}
日期转中文:
public static string DateNumToCn(DateTime dt)
{
string year = ArabicNumToCnPerDigi(dt.Year.ToString());
string month = ArabicNumToCn(dt.Month.ToString());
if (month == "壹" || month == "贰" || month == "壹拾")
{
month = "零" + month;
}
string day = ArabicNumToCn(dt.Day.ToString());
if (day.Length == 1)
{
day = "零" + day;
}
else if (day == "壹拾" || day == "贰拾" || day == "叁拾")
{
day = "零" + day;
}
return year + "年" + month + "月" + day + "日";
}
欢迎测试~~