Click here to Skip to main content
15,880,608 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Converting numbers to the word equivalent.

Rate me:
Please Sign up or sign in to vote.
4.95/5 (13 votes)
20 Aug 2010CPOL 15.7K   3   5
*Edited* EVEN MORE *Edited* Boosted Silic0re09 version. It will work with up to 10^3002 or 3003 characters or novenonagintanongentillion. I've also refactored it a bit for you to have a better grade. For sanity sake, I've put the delimiters in text files. You can download them...
*Edited* EVEN MORE *Edited* Boosted Silic0re09 version. It will work with up to 10^3002 or 3003 characters or novenonagintanongentillion. I've also refactored it a bit for you to have a better grade. For sanity sake, I've put the delimiters in text files. You can download them here:

http://www.filedropper.com/us[^]

public class NumberToWords
  {
    List<string> delims;
    List<string> teen;
    List<string> secondDigit;
    List<string> singleDigit;
    string hundred;

    //Load all the strings that will be used for the numbers.
    public NumberToWords()
    {
      delims = TextLineIntoList("US/delims.txt");
      teen = TextLineIntoList("US/teen.txt");
      secondDigit = TextLineIntoList("US/secondDigit.txt");
      singleDigit = TextLineIntoList("US/singleDigit.txt");
      hundred = TextLineIntoList("US/hundred.txt")[0];
    }
  
    //Find the max length the number can be represented.
    public int maxLength()
    {
      return (delims.Count + 1) * 3;
    }
  
    //Convert a number string to a Word.
    public string ConvertToWords(string Number)
    {
      if(!string.IsNullOrEmpty(Number))
      { 
        string numStr = Number;

        //Split the string into 3 part pieces.
        List<string> numParts = SplitNumberIntoParts(numStr);

        bool zero = true;
        for(int i = 0; i < numParts.Count && zero; i++)
        {
          zero = int.Parse(numParts[i]) == 0;
        }

        List<string> outString = new List<string>();

        if(zero)
        {
          outString.Add(singleDigit[0]);
        }
        else
        {
          int j = numParts.Count - 2;

          //For each part, translate it to text.
          for(int i = 0; i < numParts.Count; i++)
          {
            int num = int.Parse(numParts[i]);
            string temp = "";

            if(num != 0)
            {
              if(num >= 100)
              {
                // Convert numbers greater than 100.
                temp = ConvertThreeDigits(num);
              }
              else if(num >= 10)
              {
                // Convert numbers greater or equal to 10.
                temp = ConvertTwoDigits(num);
              }
              else
              {
                // Convert numbers smaller than 10
                temp = ConvertOneDigit(num);
              }

              if(j >= 0)
                temp += " " + delims[j] + ", ";
            }

            j--;

            outString.Add(temp);
          }
        }

        string retString = string.Join("", outString.ToArray());

        return retString;
      }
      else
      {
        return "";
      }
    }

    // Split each line of a text file in a List.
    private static List<string> TextLineIntoList(string path)
    {    
      TextReader tr = new StreamReader(path);
      
        string line;
        List<string> delims = new List<string>();
        
        while(!string.IsNullOrEmpty(line = tr.ReadLine()))
        {
          delims.Add(line);
        }
      
      tr.Close();
      
      return delims;
    }

    // Split string into parts of 3. First one can be less than 3.
    private List<string> SplitNumberIntoParts(string numStr)
    {
      string currentStr = "";

      int t = 0;
      for(int i = numStr.Length - 1; i >= 0; i--)
      {
        t++;
        currentStr = numStr[i] + currentStr;

        if(t == 3)
        {
          currentStr = "," + currentStr;
          t = 0;
        }
      }

      if(currentStr.StartsWith(","))
        currentStr = currentStr.Remove(0, 1);
      
      string[] vals = currentStr.Split(',');   
      List<string> result = new List<string>(vals);
      
      return result;
    }

    // Convert a number greater or equal to 100.
    private string ConvertThreeDigits(int Number)
    {
      //Get the hundreds. (ex.: 123 -> 1, 345 -> 3)
      int firstDigit = Number / 100;
      //Get the remaining numbers.
      int lastDigits = Number - (firstDigit * 100);

      //If the remaining numbers are only zeroes.
      if(lastDigits == 0)
      {
        return ConvertOneDigit(firstDigit) + " " + hundred;
      }
      else if(lastDigits <= 9)
      {
        return ConvertOneDigit(firstDigit) + " " + hundred + " " + ConvertOneDigit(lastDigits);
      }
      else
      {
        return ConvertOneDigit(firstDigit) + " " + hundred + " " + ConvertTwoDigits(lastDigits);
      }
    }

    // Convert a number greater than 9.
    private string ConvertTwoDigits(int Number)
    {
      int firstDigit = Number / 10;
      int secondDigit = Number - (firstDigit * 10);

      if(Number >= 10 && Number < 20)
      {
        return teen[secondDigit];
      }
      else
      {
        string firstPart = this.secondDigit[firstDigit -2];
        
        if(secondDigit > 0)
          firstPart += "-" + ConvertOneDigit(secondDigit);
        
        return firstPart;
      }
    }

    // Convert a number smaller than 10.
    private string ConvertOneDigit(int Number)
    {
      return singleDigit[Number];
    }
  }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer CGI
Canada Canada
I have a three years technical education in computer science (June 2006) and a four years bachelor's degree in Software Engineering from the École de Technologie Supérieure (August 2010). I worked as a Web Developper at the beginning of my career before being recruited as a .NET Analyst-Programer at SNC-Lavalin in Montreal. I worked there until they outsourced all development to CGI. I worked there since.

Comments and Discussions

 
GeneralReason for my vote of 5 gr8 Pin
divyang448221-Aug-10 9:28
professionaldivyang448221-Aug-10 9:28 
GeneralNow, it works up to novenonagintanongentillion. Pin
Simon Dufour20-Aug-10 8:23
Simon Dufour20-Aug-10 8:23 
GeneralBTW.. I detected sarcasm! Giving a right way to do it doesn'... Pin
Simon Dufour20-Aug-10 0:42
Simon Dufour20-Aug-10 0:42 
GeneralReason for my vote of 1 Failed to detect sarcasm Pin
leppie19-Aug-10 22:05
leppie19-Aug-10 22:05 
GeneralOh my. Is that actually correct up to Quadragintillion? That... Pin
Edbert P19-Aug-10 20:12
Edbert P19-Aug-10 20:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.