How to Convert Words to Numbers in C#

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.
  1. class WordsToNumbers  
  2. {  
  3.     private static Dictionary<stringlong> numberTable = new Dictionary<stringlong>{  
  4.         {"zero",0},{"one",1},{"two",2},{"three",3},{"four",4},{"five",5},{"six",6},  
  5.         {"seven",7},{"eight",8},{"nine",9},{"ten",10},{"eleven",11},{"twelve",12},  
  6.         {"thirteen",13},{"fourteen",14},{"fifteen",15},{"sixteen",16},{"seventeen",17},  
  7.         {"eighteen",18},{"nineteen",19},{"twenty",20},{"thirty",30},{"forty",40},  
  8.         {"fifty",50},{"sixty",60},{"seventy",70},{"eighty",80},{"ninety",90},  
  9.         {"hundred",100},{"thousand",1000},{"lakh",100000},{"million",1000000},  
  10.         {"billion",1000000000},{"trillion",1000000000000},{"quadrillion",1000000000000000},  
  11.         {"quintillion",1000000000000000000}  
  12.     };  
  13.   
  14.     public static long ConvertToNumbers(string numberString)  
  15.     {  
  16.         var numbers = Regex.Matches(numberString, @"\w+").Cast<Match>()  
  17.                 .Select(m => m.Value.ToLowerInvariant())  
  18.                 .Where(v => numberTable.ContainsKey(v))  
  19.                 .Select(v => numberTable[v]);  
  20.         long acc = 0, total = 0L;  
  21.         foreach (var n in numbers)  
  22.         {  
  23.             if (n >= 1000)  
  24.             {  
  25.                 total += acc * n;  
  26.                 acc = 0;  
  27.             }  
  28.             else if (n >= 100)  
  29.             {  
  30.                 acc *= n;  
  31.             }  
  32.             else acc += n;  
  33.         }  
  34.         return (total + acc) * (numberString.StartsWith("minus",  
  35.                 StringComparison.InvariantCultureIgnoreCase) ? -1 : 1);  
  36.     }  

 
 Now, call the ConvertToNumbers method.
  1. static void Main(string[] args)    
  2. {    
  3.     try    
  4.     {  
  5.         string strNumber = "Three Thsound Five Hundred Sixty Two";    
  6.         string rtnNumber = ConvertToNumbers(strNumber);    
  7.     
  8.         Console.WriteLine("Number is {0}", rtnNumber);    
  9.         Console.ReadKey();    
  10.     }    
  11.     catch (Exception ex)    
  12.     {    
  13.         Console.WriteLine(ex.Message);    
  14.     }    

 I hope this is useful for all readers. Happy Coding!

Next Recommended Reading Convert Numbers To Words In C#