Files
MsAddIns/ExportExcelTest/SimpleNumberConverter.cs
2026-02-28 21:01:57 +08:00

70 lines
2.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Generic;
/// <summary>
/// 十以内数字转换工具类
/// </summary>
public static class SimpleNumberConverter
{
private static readonly Dictionary<char, int> ChineseNumbers = new Dictionary<char, int>
{
{'零', 0}, {'一', 1}, {'二', 2}, {'三', 3}, {'四', 4},
{'五', 5}, {'六', 6}, {'七', 7}, {'八', 8}, {'九', 9},
{'壹', 1}, {'贰', 2}, {'叁', 3}, {'肆', 4}, {'伍', 5},
{'陆', 6}, {'柒', 7}, {'捌', 8}, {'玖', 9},
{'两', 2} // 特殊处理"两"
};
private static readonly Dictionary<string, int> GreekNumbers = new Dictionary<string, int>
{
{"", 1}, {"Ⅱ", 2}, {"Ⅲ", 3}, {"Ⅳ", 4}, {"", 5},
{"Ⅵ", 6}, {"Ⅶ", 7}, {"Ⅷ", 8}, {"Ⅸ", 9}
};
/// <summary>
/// 将中文数字转换为阿拉伯数字仅支持1-9
/// </summary>
/// <param name="chineseNumber">中文数字字符</param>
/// <returns>转换后的阿拉伯数字,转换失败返回-1</returns>
public static int ChineseToArabic(char chineseNumber)
{
return ChineseNumbers.TryGetValue(chineseNumber, out int result) ? result : -1;
}
/// <summary>
/// 将希腊数字转换为阿拉伯数字仅支持1-10
/// </summary>
/// <param name="greekNumber">希腊数字字符串</param>
/// <returns>转换后的阿拉伯数字,转换失败返回-1</returns>
public static int GreekToArabic(string greekNumber)
{
return GreekNumbers.TryGetValue(greekNumber, out int result) ? result : -1;
}
/// <summary>
/// 智能转换数字支持中文数字和希腊数字限10以内
/// </summary>
/// <param name="number">要转换的数字字符串</param>
/// <returns>转换后的阿拉伯数字,转换失败返回-1</returns>
public static int ToArabic(string number)
{
if (string.IsNullOrEmpty(number))
return -1;
// 尝试直接转换阿拉伯数字
if (int.TryParse(number, out int result) && result >= 0 && result < 10)
return result;
// 尝试转换希腊数字
int greek = GreekToArabic(number);
if (greek != -1)
return greek;
// 尝试转换单个中文数字
if (number.Length == 1)
return ChineseToArabic(number[0]);
return -1;
}
}