【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 => "千",
_ => ""
};
}
}