public static class ForChinese
{
static readonly Regex _nRegex = new Regex(@"[零一二三四五六七八九]+");
static readonly Regex _pRegex = new Regex(@"[十百千万亿]+");
static readonly Dictionary<char, int> _numDict = new Dictionary<char, int>
{
{ '零', 0 },
{ '一', 1 },
{ '二', 2 },
{ '三', 3 },
{ '四', 4 },
{ '五', 5 },
{ '六', 6 },
{ '七', 7 },
{ '八', 8 },
{ '九', 9 }
};
static readonly Dictionary<char, double> _postDict = new Dictionary<char, double>
{
{ '十', Math.Pow(10,1) },
{ '百', Math.Pow(10,2) },
{ '千', Math.Pow(10,3) },
{ '万', Math.Pow(10,4) },
{ '亿', Math.Pow(10,8) }
};
public static int TransNum(string num)
{
return string.IsNullOrEmpty(num) ? 0 : _numDict[num.Last()];
}
public static double TransPost(string post)
{
return post.Aggregate<char, double>(1, (current, p) => current * _postDict[p]);
}
public static double ChineseToRomanNumerals(string cn)
{
var split = cn.Split('万', '亿');
double sum = 0;
for (var i = 0; i < split.Length; i++)
{
var sp = split[i];
var str = sp;
double numSum = 0;
while (str.Length > 0)
{
// 处理数字
var nStr = _nRegex.Match(str).Value;
var n = TransNum(nStr);
// 处理数位
var pStr = _pRegex.Match(str).Value;
var p = TransPost(pStr);
// 添加数字
numSum += (n == 0 ? 1 : n) * p;
// 循环
var numPost = string.Concat(nStr, pStr);
str = str.Substring(numPost.Length);
}
var pow = split.Length - i - 1;
var post = Math.Pow(10000, pow);
sum += numSum * post;
}
return sum;
}
}
中文汉字数字转罗马数字方法
最新推荐文章于 2021-04-14 13:45:45 发布