Introduction
In this blog, I have described how to convert words to numeric values.
For example:
Input = Three Thousand Five Hundred Sixty Two
Output = 3562
The function is named "ConvertToNumbers" and accepts a parameter of type string and returns a number value containing the words in number.
- class WordsToNumbers
- {
- private static Dictionary<string, long> numberTable = new Dictionary<string, long>{
- {"zero",0},{"one",1},{"two",2},{"three",3},{"four",4},{"five",5},{"six",6},
- {"seven",7},{"eight",8},{"nine",9},{"ten",10},{"eleven",11},{"twelve",12},
- {"thirteen",13},{"fourteen",14},{"fifteen",15},{"sixteen",16},{"seventeen",17},
- {"eighteen",18},{"nineteen",19},{"twenty",20},{"thirty",30},{"forty",40},
- {"fifty",50},{"sixty",60},{"seventy",70},{"eighty",80},{"ninety",90},
- {"hundred",100},{"thousand",1000},{"lakh",100000},{"million",1000000},
- {"billion",1000000000},{"trillion",1000000000000},{"quadrillion",1000000000000000},
- {"quintillion",1000000000000000000}
- };
-
- public static long ConvertToNumbers(string numberString)
- {
- var numbers = Regex.Matches(numberString, @"\w+").Cast<Match>()
- .Select(m => m.Value.ToLowerInvariant())
- .Where(v => numberTable.ContainsKey(v))
- .Select(v => numberTable[v]);
- long acc = 0, total = 0L;
- foreach (var n in numbers)
- {
- if (n >= 1000)
- {
- total += acc * n;
- acc = 0;
- }
- else if (n >= 100)
- {
- acc *= n;
- }
- else acc += n;
- }
- return (total + acc) * (numberString.StartsWith("minus",
- StringComparison.InvariantCultureIgnoreCase) ? -1 : 1);
- }
- }
Now, call the ConvertToNumbers method.
- static void Main(string[] args)
- {
- try
- {
- string strNumber = "Three Thsound Five Hundred Sixty Two";
- string rtnNumber = ConvertToNumbers(strNumber);
-
- Console.WriteLine("Number is {0}", rtnNumber);
- Console.ReadKey();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
I hope this is useful for all readers. Happy Coding!