kick it on DotNetKicks.com

Earlier this week I received a request from on one of my projects to allow the user to enter only the number (ex. 14) on a web form, but when the number is used in other areas of the project for the number to be shown as fourteen. So, I initially hoped there would be a built in function in C# to allow for this conversion. I wasn't able to find a function to do this out of the box.

A co-worker and I decided to set out to write our own function to accomplish the task. We decided to create the function as a static method in a helper class so that we could call the method from anywhere in the project.

The function is able to convert numbers to word from zero up through the billions. I guess you could always add larger numbers to the function if needed.

Here is the C# code that we came up with:

 
   1: public static string ConvertNumberToWord(long numberVal)
   2: {
   3:    string[] powers = new string[] { "thousand ", "million ", 
   4:       "billion " };
   5:  
   6:    string[] ones = new string[] {"one", "two", "three", "four", 
   7:       "five", "six", "seven", "eight", "nine", "ten",
   8:       "eleven", "twelve", "thirteen", "fourteen", "fifteen",
   9:       "sixteen", "seventeen", "eighteen", "nineteen"};
  10:  
  11:    string[] tens = new string[] {"twenty", "thirty", "forty", 
  12:       "fifty", "sixty", "seventy", "eighty", "ninety"};
  13:  
  14:    string wordValue = "";
  15:  
  16:    if (numberVal == 0) return "zero";
  17:    if (numberVal < 0)
  18:    {
  19:       wordValue = "negative ";
  20:       numberVal = -numberVal;
  21:    }
  22:  
  23:    long[] partStack = new long[] { 0, 0, 0, 0 };
  24:    int partNdx = 0;
  25:  
  26:    while (numberVal > 0)
  27:    {
  28:       partStack[partNdx++] = numberVal % 1000;
  29:       numberVal /= 1000;
  30:    }
  31:  
  32:    for (int i = 3; i >= 0; i--)
  33:    {
  34:       long part = partStack[i];
  35:  
  36:       if (part >= 100)
  37:       {
  38:          wordValue += ones[part / 100 - 1] + " hundred ";
  39:          part %= 100;
  40:       }
  41:  
  42:       if (part >= 20)
  43:       {
  44:          if ((part % 10) != 0) wordValue += tens[part / 10 - 2] + 
  45:             " " + ones[part % 10 - 1] + " ";
  46:          else wordValue += tens[part / 10 - 2] + " ";
  47:       }
  48:       else if (part > 0) wordValue += ones[part - 1] + " ";
  49:  
  50:       if (part != 0 && i > 0) wordValue += powers[i - 1];
  51:    }
  52:  
  53:    return wordValue;
  54: }

Let me know in the comments what you think about the function. If you can find any way to make improvements to the function, please include those in the comments as well.