Make an extension method to convert numbers into words (as in “one thousand eight hundred twelve”) in C#

This example builds the ToWords extension method to convert numbers into words. (For example, converting 1,337 into “one thousand, three hundred thirty seven.) The method extends the double class, and is implemented in the static class DoubleExtensions.

The following code shows the extension method.

// Convert a double into words. 
// E.g. "one thousand eight hundred twelve."
public static string ToWords(this double num)
{
    // Return a word representation of the whole number value.
    // Remove any fractional part.
    num = Math.Truncate(num);

    // If the number is 0, return zero.
    if (num == 0) return "zero";

    string[] groups = {"", "thousand", "million", "billion",
        "trillion", "quadrillion", "?", "??", "???", "????"};
    string result = "";

    // Process the groups, smallest first.
    int group_num = 0;
    while (num > 0)
    {
        // Get the next group of three digits.
        double quotient = Math.Truncate(num / 1000);
        int remainder = (int)Math.Round(num - quotient * 1000);
        num = quotient;

        // Convert the group into words.
        if (remainder != 0)
            result = GroupToWords(remainder) +
                " " + groups[group_num] + ", " +
                result;

        // Get ready for the next group.
        group_num++;
    }

    // Remove the trailing ", ".
    if (result.EndsWith(", "))
        result = result.Substring(0, result.Length - 2);

    return result.Trim();
}

The method first truncates its parameter to get an integer. If the number is 0, the method returns “zero.” The code defines grouping names: thousand, million, and so forth. It then starts the more interesting processing.

The code enters a loop that examines the number in three-digit chunks, smallest to largest. It starts with the digits under a thousand, then works up through thousands, millions, and so forth.

To get a chunk, the code calculates a quotient by dividing the number by 1000 and truncates to get an integer. That represents the number’s value after removing the smallest chunk. For example, with the value 123,456, dividing by 1000 and truncating gives 123.

To get the next chunk, the code multiplies the quotient by 1000 and subtracting from the original number. For 123,456, the code subtracts 123,456 – 123,000 to get the first chunk to process: 456.

The method then calls the GroupToWords method to convert the three-digit chunk into words. The method adds the new chunk, the appropriate group name (thousands, millions, etc.), and a comma to the beginning of the growing result string.

Before exiting, the GroupToWords method removes any trailing comma added after the first group.

The following code shows the GroupToWords method.

// Convert a number between 0 and 999 into words.
private static string GroupToWords(int num)
{
    string[] one_to_nineteen = {"zero", "one", ... , "nineteen"};
    string[] multiples_of_ten = {"twenty", "thirty", ..., "ninety"};

    // If the number is 0, return an empty string.
    if (num == 0) return "";

    // Handle the hundreds digit.
    int digit;
    string result = "";
    if (num > 99)
    {
        digit = (int)(num / 100);
        num = num % 100;
        result = one_to_nineteen[digit] + " hundred";
    }

    // If num = 0, we have hundreds only.
    if (num == 0) return result.Trim();

    // See if the rest is less than 20.
    if (num < 20)
    {
        // Look up the correct name.
        result += " " + one_to_nineteen[num];
    }
    else
    {
        // Handle the tens digit.
        digit = (int)(num / 10);
        num = num % 10;
        result += " " + multiples_of_ten[digit - 2];

        // Handle the final digit.
        if (num > 0)
            result += " " + one_to_nineteen[num];
    }

    return result.Trim();
}

The GroupToWords method starts by defining names for values between 0 and 19, and for multiples of 10.

Next if the number is greater than 99, the function gets the hundreds digit and uses the one_to_nineteen array to look up its string representation. It adds that representation plus the word “hundred” to the result. If the number has no other digits, the function returns what it has so far.

Then if the remaining number is less than 20, the function uses the one_to_nineteen array to look up the number’s representation and adds it to the result.

If the number is greater than 19, the function gets the tens digit and uses the multiples_of_ten array to get add its representation to the result.

Finally the method uses the one_to_nineteen array to add on the representation of the ones digit.






This entry was posted in algorithms, extension methods, mathematics and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink.

6 Responses to Make an extension method to convert numbers into words (as in “one thousand eight hundred twelve”) in C#

  1. getmscode says:

    Its really nice post, to see the similar and simple implementation you can see the below link also;

    http://www.getmscode.com/2014/12/convert-number-to-words-c-code.html

  2. Jacob Augustine says:

    thanks alot, i wil like to train wit you. What is the cost

    • RodStephens says:

      Unless you’re local, I probably can’t tutor you very effectively. It would be pretty expensive, too.

      But you can get my books and my video training courses. See these links:

      Or search Barnes & Noble, Amazon, or your favorite online bookstore.

  3. Mohamed Shakir says:

    This code is really nice. But there are some mistakes if we convert one million it shows “One Million, Thousand” like this

Leave a Reply

Your email address will not be published. Required fields are marked *