Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Converting numbers to the word equivalent.

, 20 Aug 2010
Rate this:
Please Sign up or sign in to vote.
*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)

About the Author

Simon Dufour
Software Developer SNC-Lavalin inc.
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.
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralBTW.. I detected sarcasm! Giving a right way to do it doesn'... PinmemberSimon Dufour20-Aug-10 0:42 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 20 Aug 2010
Article Copyright 2010 by Simon Dufour
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid