C# int 数字转 中文字符串

    static char[] cnArr = new char[] { '零', '一', '二', '三', '四', '五', '六', '七', '八', '九'};
    static string[] linkArr1 = new string[] { "","十", "百", "千"};
    static string[] linkArr2 = new string[] { "","万", "亿", "万" };
    /// 将数字转化为中文字符串
    /// 
    public static string ToStringCNNum(this int num)
    {
        bool isNative = num >= 0;
        num = Math.Abs(num);
        StringBuilder ret = new StringBuilder();
        for(int i = 0; num != 0; ++i)
        {
            int n = num % 10000;
            num /= 10000;
            if (n != 0) //添加高位标识
                ret.Append(linkArr2[i]);
            for (int j = 0; j < 4; ++j)
            {
                int m = n % 10;
                n /= 10;
                if (m != 0) //添加低位标识
                    ret.Append(linkArr1[j]);
                //如果更高位没有任何数字则跳过 / 如果前一位不存在或为"零"则跳过
                else if ((n == 0 && num == 0) || ret.Length == 0 || ret[ret.Length - 1] == cnArr[0])    
                    continue;
                ret.Append(cnArr[m]);
            }
        }
        //替换"一十"和移除不需要的0
        ret.Replace("十一", "十");
        for (int i = ret.Length - 1; i > 0; --i)
        {
            if (ret[i] == cnArr[0] && linkArr2.Contains(new string(new char[] { ret[i - 1] })))
            {
                ret.Remove(i, 1);
            }
        }
        ret.Append(isNative ? "" : "负");
        return ret.ToString().Reverse();
    }

    /// 字符串翻转
    public static string Reverse(this string str)
    {
        var arr = str.ToCharArray().Reverse().ToArray();
        return new string(arr);
    }

你可能感兴趣的:(Unity,c#,算法)