志在指尖
用双手敲打未来

阿拉伯数字转换为中文数字/中文数字转换为阿拉伯数字

项目中经常会格式化数据,转换数字的运用状况比拟多,记载一下数字转换的办法!
假如需求转换为繁体中文,将数组里的汉字换成繁体中文即可。C#
1.阿拉伯数字转换为中文数字
复制代码
1///
2///阿拉伯数字转换成中文数字
3///
4///
5///
6publicstringNumToChinese(stringx)
7{
8string[]pArrayNum={“零”,”一”,”二”,”三”,”四”,”五”,”六”,”七”,”八”,”九”};
9//为数字位数树立一个位数组
10string[]pArrayDigit={“”,”十”,”百”,”千”};
11//为数字单位树立一个单位数组
12string[]pArrayUnits={“”,”万”,”亿”,”万亿”};
13varpStrReturnValue=””;//返回值
14varfinger=0;//字符位置指针
15varpIntM=x.Length%4;//取模
16intpIntK;
17if(pIntM>0)
18pIntK=x.Length/4+1;
19else
20pIntK=x.Length/4;
21//外层循环,四位一组,每组最后加上单位:”,万亿,”,”,亿,”,”,万,”
22for(vari=pIntK;i>0;i–)
23{
24varpIntL=4;
25if(i==pIntK&&pIntM!=0)
26pIntL=pIntM;
27//得到一组四位数
28varfour=x.Substring(finger,pIntL);
29varP_int_l=four.Length;
30//内层循环在该组中的每一位数上循环
31for(intj=0;j<P_int_l;j++)
32{
33//处置组中的每一位数加上所在的位
34intn=Convert.ToInt32(four.Substring(j,1));
35if(n==0)
36{
37if(j<P_int_l-1&&Convert.ToInt32(four.Substring(j+1,1))>0&&!pStrReturnValue.EndsWith(pArrayNum[n]))
38pStrReturnValue+=pArrayNum[n];
39}
40else
41{
42if(!(n==1&&(pStrReturnValue.EndsWith(pArrayNum[0])|pStrReturnValue.Length==0)&&j==P_int_l-2))
43pStrReturnValue+=pArrayNum[n];
44pStrReturnValue+=pArrayDigit[P_int_l-j-1];
45}
46}
47finger+=pIntL;
48//每组最后加上一个单位:”,万,”,”,亿,”等
49if(i<pIntK)//假如不是最高位的一组
50{
51if(Convert.ToInt32(four)!=0)
52//假如一切4位不全是0则加上单位”,万,”,”,亿,”等
53pStrReturnValue+=pArrayUnits[i-1];
54}
55else
56{
57//处置最高位的一组,最后必需加上单位
58pStrReturnValue+=pArrayUnits[i-1];
59}
60}
61returnpStrReturnValue;
62}
复制代码
2.中文数字转换为阿拉伯数字
复制代码
1///
2///转换数字
3///
4protectedstaticlongCharToNumber(charc)
5{
6switch(c)
7{
8case’一’:return1;
9case’二’:return2;
10case’三’:return3;
11case’四’:return4;
12case’五’:return5;
13case’六’:return6;
14case’七’:return7;
15case’八’:return8;
16case’九’:return9;
17case’零’:return0;
18default:return-1;
19}
20}
21
22///
23///转换单位
24///
25protectedstaticlongCharToUnit(charc)
26{
27switch(c)
28{
29case’十’:return10;
30case’百’:return100;
31case’千’:return1000;
32case’万’:return10000;
33case’亿’:return100000000;
34default:return1;
35}
36}
37///
38///将中文数字转换阿拉伯数字
39///
40///汉字数字
41///长整型阿拉伯数字
42publicstaticlongParseCnToInt(stringcnum)
43{
44cnum=Regex.Replace(cnum,”\\s+”,””);
45longfirstUnit=1;//一级单位
46longsecondUnit=1;//二级单位
47longresult=0;//结果
48for(vari=cnum.Length-1;i>-1;–i)//从低到高位依次处置
49{
50vartmpUnit=CharToUnit(cnum[i]);//暂时单位变量
51if(tmpUnit>firstUnit)//判别此位是数字还是单位
52{
53firstUnit=tmpUnit;//是的话就赋值,以备下次循环运用
54secondUnit=1;
55if(i==0)//处置假如是”十”,”十一”这样的开头的
56{
57result+=firstUnit*secondUnit;
58}
59continue;//完毕本次循环
60}
61if(tmpUnit>secondUnit)
62{
63secondUnit=tmpUnit;
64continue;
65}
66result+=firstUnit*secondUnit*CharToNumber(cnum[i]);//假如是数字,则和单位想乘然后存到结果里
67}
68returnresult;
69}

未经允许不得转载:IT技术网站 » 阿拉伯数字转换为中文数字/中文数字转换为阿拉伯数字
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载