public class Program
{
public static void Main(string[] args)
{
bool exit = false;
while (!exit)
{
Console.WriteLine("请输入一个数字(输入n退出):");
string input = Console.ReadLine();
if (input == "n")
{
exit = true;
}
else
{
if (decimal.TryParse(input, out decimal number))
{
string chineseAmount = NumberToChineseAmount.ConvertToChineseAmount(number);
Console.WriteLine(chineseAmount);
}
else
{
Console.WriteLine("输入无效,请重新输入。");
}
}
}
}
}
public class NumberToChineseAmount
{
private static readonly string[] ChineseNumbers = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
private static readonly string[] ChineseUnits = { "", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟" };
private static readonly string[] ChineseUnits2 = { "角", "分" };
public static string ConvertToChineseAmount(decimal number)
{
string amount = number.ToString("0.00");
string[] parts = amount.Split('.');
string integerPart = ConvertIntegerPart(parts[0]);
string decimalPart = ConvertDecimalPart(parts[1]);
return integerPart + "元" + decimalPart;
}
private static string ConvertIntegerPart(string integerPart)
{
string result = "";
int length = integerPart.Length;
for (int i = 0; i < length; i++)
{
int digit = int.Parse(integerPart[i].ToString());
string chineseNumber = ChineseNumbers[digit];
string chineseUnit = ChineseUnits[length - 1 - i];
if (digit == 0)
{
if (i < length - 1 && int.Parse(integerPart[i + 1].ToString()) != 0)
{
result += chineseNumber;
}
}
else
{
result += chineseNumber + chineseUnit;
}
}
if (result == "")
{
result = "零";
}
return result;
}
private static string ConvertDecimalPart(string decimalPart)
{
string result = "";
int firstDigit = int.Parse(decimalPart[0].ToString());
int secondDigit = int.Parse(decimalPart[1].ToString());
if (firstDigit == 0 && secondDigit == 0)
{
result = "整";
}
else
{
if (firstDigit != 0)
{
result += ChineseNumbers[firstDigit] + ChineseUnits2[0];
}
else
{
result += "零角";
}
if (secondDigit != 0)
{
result += ChineseNumbers[secondDigit] + ChineseUnits2[1];
}
}
return result;
}
}