【C#】将数字转换为中文,如123转换为一百二十三

一、数字转换为中文数字

今天项目中遇到一个问题,就是数字转换为中文数字显示,这其中有很多麻烦的地方处理,比如100会显示为一百,而不是一百零;1001会显示为一千零一,而不是一千零零一;150会显示为一百五,而不是一百五十或者一百五零,等等问题,真是感叹中文数字叫法的多种多样,中华文化的博大精深。

二、代码

话不多说,直接上代码,直接写了一个静态类,传入数字就可以了

using System.Collections.Generic;


public static class NumberConverter
{
    public static string NumberToChinese(int number)
    {
        if (number == 0) return "零";

        string[] digits = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
        List<string> result = new List<string>();
        int unit = 1;
        int currentNumber = number;
        bool hasNonZero = false;

        while (currentNumber > 0)
        {
            int digit = currentNumber % 10;
            currentNumber /= 10;

            if (digit == 0)
            {
                // 处理零的情况(非末尾且前面有非零数字时添加)
                if (currentNumber > 0 && hasNonZero && (result.Count == 0 || result[^1] != "零"))
                {
                    result.Add(digits[digit]);
                }
            }
            else
            {
                // 处理单位(十位为1且非末尾时添加"一十")
                string unitStr = unit switch
                {
                    10 when digit == 1 && currentNumber > 0 => "十",
                    _ => GetUnit(unit)
                };
                result.Add($"{digits[digit]}{unitStr}");
                hasNonZero = true;
            }

            unit *= 10;
        }

        // 反转并清理末尾零
        result.Reverse();
        while (result.Count > 0 && result[^1] == "零")
        {
            result.RemoveAt(result.Count - 1);
        }

        return string.Join("", result);
    }

    private static string GetUnit(int unit)
    {
        return unit switch
        {
            1 => "",
            10 => "十",
            100 => "百",
            1000 => "千",
            _ => ""
        };
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

七月.末

你的鼓励就是我创作的最大动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值