中文漢字數字轉羅馬數字方法
阿新 • • 發佈:2018-12-27
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; } }