c#将int转为中文数字

发布于:2024-09-17 ⋅ 阅读:(145) ⋅ 点赞:(0)
public static string IntegerToCN(int value)
        {
            string[] numberStrs = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
            if (value <= 10)
            {
                value = Math.Max(0, value);
                return numberStrs[value];
            }
            string[] unitStrs = { "十", "百", "千", "", "十", "百", "千", "" };
            string unitWan = "万", unitYi = "亿";
            StringBuilder stringBuilder = new StringBuilder();
            int unitIndex = unitStrs.Length - 1;
            int unitInteger = 1_0000_0000;
            bool addZero = false;

            while (unitInteger > 0)
            {
                int value1 = value / unitInteger;
                if (value1 > 0)
                {
                    if (addZero)
                    {
                        stringBuilder.Append(numberStrs[0]);
                        addZero = false;
                    }

                    stringBuilder.Append(numberStrs[value1]);
                    if (unitIndex >= 0)
                    {
                        stringBuilder.Append(unitStrs[unitIndex]);
                    }
                    var newValue = value - value1 * unitInteger;
                    if (newValue < unitInteger / 10)
                    {
                        addZero = true;
                    }
                    if (value >= 1_0000_0000 && newValue < 1_0000_0000)
                    {
                        stringBuilder.Append(unitYi);
                    }
                    else if (value >= 1_0000 && newValue < 1_0000)
                    {
                        stringBuilder.Append(unitWan);
                    }
                    value = newValue;
                }
                unitIndex--;
                unitInteger = unitInteger / 10;
            }
            return stringBuilder.ToString();
        }
            while (true)
            {
                var inputStr = Console.ReadLine();
                Console.WriteLine(IntegerToCN(int.Parse(inputStr)));
            }

测试: 输入: 123456789
输出: 一亿二千三百四十五万六千七百八十九


网站公告

今日签到

点亮在社区的每一天
去签到