前几天有人在群里写这个,好像挺纠结的样子,就顺手帮他写了一个。
主要思路是中文的数字读法是四位四位分的,高位数字的读法就是xxxx亿xxxx万xxxx。
void Start () { //测试数据 Debug.Log (full_toword(987654321)); Debug.Log (full_toword(907654321)); Debug.Log (full_toword(9000900654321)); Debug.Log (full_toword(9000900000000)); } string full_toword(long i){ long[] a=new long[4];//按照万亿兆拆分输入数字 a [0] = i/1000000000000; a [1] = i / 100000000 % 10000; a [2] = i / 10000 % 10000; a [3] = i % 10000; string[] s = new string[4];//每4位数字对应的字符串 s [0] = thousand_toword ((int)a [0],"兆"); s [1] = thousand_toword ((int)a [1],"亿"); s [2] = thousand_toword ((int)a [2],"万"); s [3] = thousand_toword ((int)a [3],""); for (int j = 0; j < 4; j++) { if (0 == a [j]) s [j] = "";//除去高位零 else break; } for (int j = 3; j >= 0; j--) { if (0 == a [j]) s [j] = "";//除去低位零 else break; } int max;//获取数字中最大的单位 for (max = 0; max < 4; max++) { if (a [max] != 0) break; } for (int j = max + 1; j < 4; j++) { if ((0 != a [j]) && (a [j] / 1000 == 0)) s [j] = "零" + s [j];//如果该四位数字不是零,并且不是最高位,那么在前面加一个零 } string _out = s[0]+s[1]+s[2]+s[3]; return _out; } ///输出四位数字的读法 string thousand_toword(int i,string ss){ int[] a=new int[4]; a [0] = i / 1000; a [1] = i / 100 % 10; a [2] = i / 10 % 10; a [3] = i % 10; string[] s = new string[4]; s [0] = toword (a [0],"千"); s [1] = toword (a [1],"百"); s [2] = toword (a [2],"十"); s [3] = toword (a [3],""); for (int j = 0; j < 4; j++) { if (0 == a [j]) s [j] = "";//除去高位零 else break; } for (int j = 3; j >= 0; j--) { if (0 == a [j]) s [j] = "";//除去低位零 else break; } for (int j = 0; j < 3; j++) { if (("零" == s [j]) && ("零" == s [j+1])) s [j] = "";//将连续的零合并为一个,比如1001这样的数字 } string _out = s[0]+s[1]+s[2]+s[3]+ss; return _out; } //将对应的一位阿拉伯数字转换为汉字 string toword(int i,string s){ switch (i) { case 0: return("零"); case 1: return("一"+s); case 2: return("二"+s); case 3: return("三"+s); case 4: return("四"+s); case 5: return("五"+s); case 6: return("六"+s); case 7: return("七"+s); case 8: return("八"+s); case 9: return("九"+s); default: return(""); } } }
附一张输出结果,没问题
时间: 2024-10-23 08:56:06