数値から英語読みに変換するあまり需要のないコンバータ。
Project Euler Problem 17のために作ったw
数値から英語読みに変換するあまり需要のないコンバータ。
Project Euler Problem 17のために作ったw
class EnglishConverter { static readonly string[] underTwenty = { "zero" , "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ,"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; static readonly string[] ten = { "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; static readonly string[] largeNumbers = { "thousand", "million", "billion", "trillion", "quadrillion", "quintillion" }; public enum Format { England , American } public static string ToString(long number, Format format = Format.American) { if (number < 0) { return string.Format("{0} {1}", format==Format.England ? "minus" : "negative", ToString(number * -1, format)); } else if (number < 20) { return underTwenty[(int)number]; } else { StringBuilder sb = new StringBuilder(); if (number < 100) { long onevalue; long tenvalue = Math.DivRem(number, 10, out onevalue) - 1; sb.Append(ten[(int)tenvalue]); if (onevalue != 0) { sb.AppendFormat("-{0}", ToString(onevalue, format)); } } else if (number < 1000) { long rem; long div = Math.DivRem(number, 100, out rem); sb.AppendFormat("{0} hundred", ToString(div, format)); if (rem != 0) { sb.AppendFormat(" {0}{1}", (format==Format.England)? "and " : "", ToString(rem)); } } else { for (int i = 0; i < largeNumbers.Length; ++i) { if (number < Math.Pow(1000, i + 2)) { long rem; long div = Math.DivRem(number, (long)Math.Pow(1000, i + 1), out rem); sb.AppendFormat("{0} {1}", ToString(div, format), largeNumbers[i]); if (rem != 0) { sb.AppendFormat(" {0}{1}", (format == Format.England) ? "and " : "", ToString(rem)); } break; } } } return sb.ToString(); } } }