How can I convert an integer into its verbal representation?

Viewed 48150

Is there a library or a class/function that I can use to convert an integer to it's verbal representation?

Example input:

4,567,788`

Example output:

Four million, Five hundred sixty-seven thousand, seven hundred eighty-eight

15 Answers

Fully recursive version:

private static string[] ones = {
    "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", 
    "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen",
};

private static string[] tens = { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

private static string[] thous = { "hundred", "thousand", "million", "billion", "trillion", "quadrillion" };

private static string fmt_negative = "negative {0}";
private static string fmt_dollars_and_cents = "{0} dollars and {1} cents";
private static string fmt_tens_ones = "{0}-{1}"; // e.g. for twenty-one, thirty-two etc. You might want to use an en-dash or em-dash instead of a hyphen.
private static string fmt_large_small = "{0} {1}"; // stitches together the large and small part of a number, like "{three thousand} {five hundred forty two}"
private static string fmt_amount_scale = "{0} {1}"; // adds the scale to the number, e.g. "{three} {million}";

public static string ToWords(decimal number) {
    if (number < 0)
        return string.format(fmt_negative, ToWords(Math.Abs(number)));

    int intPortion = (int)number;
    int decPortion = (int)((number - intPortion) * (decimal) 100);

    return string.Format(fmt_dollars_and_cents, ToWords(intPortion), ToWords(decPortion));
}

private static string ToWords(int number, string appendScale = "") {
    string numString = "";
    // if the number is less than one hundred, then we're mostly just pulling out constants from the ones and tens dictionaries
    if (number < 100) {
        if (number < 20)
            numString = ones[number];
        else {
            numString = tens[number / 10];
            if ((number % 10) > 0)
                numString = string.Format(fmt_tens_ones, numString, ones[number % 10]);
        }
    } else {
        int pow = 0; // we'll divide the number by pow to figure out the next chunk
        string powStr = ""; // powStr will be the scale that we append to the string e.g. "hundred", "thousand", etc.

        if (number < 1000) { // number is between 100 and 1000
            pow = 100; // so we'll be dividing by one hundred
            powStr = thous[0]; // and appending the string "hundred"
        } else { // find the scale of the number
            // log will be 1, 2, 3 for 1_000, 1_000_000, 1_000_000_000, etc.
            int log = (int)Math.Log(number, 1000);
            // pow will be 1_000, 1_000_000, 1_000_000_000 etc.
            pow = (int)Math.Pow(1000, log);
            // powStr will be thousand, million, billion etc.
            powStr = thous[log];
        }

        // we take the quotient and the remainder after dividing by pow, and call ToWords on each to handle cases like "{five thousand} {thirty two}" (curly brackets added for emphasis)
        numString = string.Format(fmt_large_small, ToWords(number / pow, powStr), ToWords(number % pow)).Trim();
    }

    // and after all of this, if we were passed in a scale from above, we append it to the current number "{five} {thousand}"
    return string.Format(fmt_amount_scale, numString, appendScale).Trim();
}

Current works up to the (short scale) quadrillions. Additional support (for larger numbers, or for the long scale) can be added simply by changing the thous variable.

I was tasked to create a WEB API that converts numbers to words using C#.

Can be whole number or with decimal points in 48 hours time.

The call will be coming from a front-end application using Ajax Post method and return the converted result in the webpage.

I've publicly shared that project in the GitHub for reference: https://github.com/marvinglennlacuna/NumbersToWordsConverter.Api

With the following technical implementatation in placed:

  1. MVC structured
  2. API Controller
  3. Service
  4. Model
  5. Error Handling
  6. Unit Testing using MSTest
  7. Code Coverage - 98%
  8. Jquery

And with technical documentation about the following as well:

  1. Purpose
  2. Prerequisites
  3. Functionl Requirements
  4. Process Diagram and Output

**Result via Web Page (US-001) **

US-001 Convert Numbers to Words via web page process

enter image description here

US-001 Convert Numbers to Words via web page output

enter image description here

Result via Postman (US-002)

US-002 - Convert Numbers to Words via Postman process

enter image description here

US-002 - Convert Numbers to Words via Postman output

enter image description here

I think it's just worth sharing a working solution in the case you need it for reference in interview/code test/school or for fun only.

Cheers, Marvin

New Method April 2022: To Convert Integers to Words in C#

Although a late answer, but in case someone arrives to this page after googling.

I have written the following C# function NumIntToWords(String NumIn) that provides a simple, short, and efficient method of converting integer numbers to words in C# complying with the US English Grammar Rules.

The function uses my devised method of SLST (Single Loop String Triplet).

Unlike other methods I had seen used here and elsewhere, the function has the following features:

  • Simple, short, and fast.
  • It does not use switch/case statements.
  • It does require the use of extra spaces in strings or trimming strings.
  • It does not use recursion.
  • It does not use math functions (only one math for creating the string triplet).
  • You can simply increase scale beyond Trillion by a simple increase of the scale array without any additional coding necessary.
  • It compiles into a very shortcode.
  • No extra libraries.

I have opted for the integer number to be converted to be passed as a string so you can handle very large integer numbers easily.

You can use it like this:

Console.WriteLine( NumIntToWords("1991345678974"));

\\ Output:

One Trillion Nine Hundred Ninety-One Billion Three Hundred Forty-Five Million Six Hundred Seventy-Eight Thousand Nine Hundred Seventy-Four

C# SLST Function Method (c) Mohsen Alyafei:

/*********************************************************************
* @function    : NumIntToWords(String NumIn)
* @purpose     : Converts Unsigned Integers to Words
*                Using the SLST Method (C) Mohsen Alyafei 2019.
*                Does not check for Non-Numerics or +/- signs
* @version     : 2.11
* @author      : Mohsen Alyafei
* @Licence     : MIT
* @date        : 03 April 2022
* @in_param    : {NumIn} (Required): Number in string format
* @returns     : {string}: The number in English Words US Grammar
**********************************************************************/
public static string NumIntToWords(String NumIn) {
if (NumIn.TrimStart('0')=="") return "Zero";                   // If empty or zero return Zero

string[] T10s= {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"},
         T20s= {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"},
       Scales= {"","Thousand","Million","Billion","Trillion"};// increase scale here (unlimited)
NumIn = new String('0', NumIn.Length * 2 % 3) + NumIn;        // Make it a String Triplet
String numToWords= "", wordTriplet, Triplet;

for (int digits = NumIn.Length; digits > 0; digits -= 3)  {   // Single Loop
    Triplet = NumIn.Substring(NumIn.Length - digits, 3);      // Get next Triplet
    if (Triplet != "000") {                                   // Convert Only if not empty
      wordTriplet="";
      int ScalePos= digits / 3 - 1,                           // Scale name position
              hund= int.Parse(""+Triplet[0]),
              tens= int.Parse(Triplet.Substring(1,2)),
              ones= int.Parse(""+Triplet[2]);
       wordTriplet= (hund>0 ? T10s[hund] + " Hundred" :"") +
                    (tens>0 && hund>0 ?" ":"") +
                    (tens<20 ? T10s[tens]: T20s[int.Parse(""+Triplet[1])]+(ones>0? "-"+T10s[ones]:"")) +
                    (ScalePos>0?" ":"")+ Scales[ScalePos];    // Add Scale Name to Triplet Word
       numToWords+= (numToWords!=""?" ":"") + wordTriplet;    // Concat Next Triplet Word
      }
}                   // Loop for the next Triplet
return numToWords;  // Return full Number in Words
}
Related