SIGN UP MEMBER LOGIN:    
ARTICLE

Converting Numbers to Words in C#

Posted by Vulpes Articles | C# Language March 25, 2011
This article shows how to convert a number to words.
Reader Level:

Introduction

A question which is often asked on programming forums is - how do I convert a number to words?

Although many solutions have been posted over the years, we appear to be lacking a basic article on the subject here on C# Corner.

In this article, I'd therefore like to present a simple program which I've written to deal with this question for integers in the range of an Int32 (about plus or minus 2 billion) which I believe is the most useful case.

The program supports both the US and UK numbering systems. For example the number 620 would be expressed as follows:

    Six Hundred Twenty   (in the US system)
    Six Hundred and Twenty  (in the UK system)

Source Code

using System;
class Program
{
    static void Main()
    {
        string input;
        int number;
        bool isValid;
        bool isUK = false;
        Console.WriteLine("\nEnter '0' to quit the program at any time\n");
        while (true)
        {
            Console.Write("\nUse UK numbering y/n : ");
            input = Console.ReadLine();
            if (!(input.ToLower() == "y" || input.ToLower() == "n"))
                Console.WriteLine("\n  Must be 'y' or 'n', please try again\n");
            else
            {
                if (input.ToLower() == "y") isUK = true;
                Console.WriteLine("\n");
                break;
            }
        }
        do
        {
            Console.Write("Enter integer : ");
            input = Console.ReadLine();
            isValid = int.TryParse(input, out number);
            if (!isValid)
                Console.WriteLine("\n  Not an integer, please try again\n");
            else
                Console.WriteLine("\n  {0}\n", NumberToText(number, isUK));
        }
        while (!(isValid && number == 0));
        Console.WriteLine("\nProgram ended");
    }
    public static string NumberToText(int number, bool isUK)
    {
        if (number == 0) return "Zero";
        string and = isUK ? "and " : ""; // deals with UK or US numbering
        if (number == -2147483648) return "Minus Two Billion One Hundred " + and +
        "Forty Seven Million Four Hundred " + and + "Eighty Three Thousand " +
        "Six Hundred " + and + "Forty Eight";
        int[] num = new int[4];
        int first = 0;
        int u, h, t;
        System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
        if (number < 0)
        {
            sb.Append("Minus ");
            number = -number;
        }
        string[] words0 = {"", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine "};
        string[] words1 = {"Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "};
        string[] words2 = {"Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "};
        string[] words3 = { "Thousand ", "Million ", "Billion " };
        num[0] = number % 1000;           // units
        num[1] = number / 1000;
        num[2] = number / 1000000;
        num[1] = num[1] - 1000 * num[2];  // thousands
        num[3] = number / 1000000000;     // billions
        num[2] = num[2] - 1000 * num[3];  // millions
        for (int i = 3; i > 0; i--)
        {
            if (num[i] != 0)
            {
                first = i;
                break;
            }
        }
        for (int i = first; i >= 0; i--)
        {
            if (num[i] == 0) continue;
            u = num[i] % 10;              // ones
            t = num[i] / 10;
            h = num[i] / 100;             // hundreds
            t = t - 10 * h;               // tens
            if (h > 0) sb.Append(words0[h] + "Hundred ");
            if (u > 0 || t > 0)
            {
                if (h > 0 || i < first) sb.Append(and);
                if (t == 0)
                    sb.Append(words0[u]);
                else if (t == 1)
                    sb.Append(words1[u]);
                else
                    sb.Append(words2[t - 2] + words0[u]);
            }
            if (i != 0) sb.Append(words3[i - 1]);
        }
        return sb.ToString().TrimEnd();
    }
}

Conclusion

It would not be difficult to extend this program to deal with larger integers, with decimal numbers or with specific currencies and I leave this as an exercise to those who need this functionality.

Login to add your contents and source code to this article
share this article :
post comment
 

If you check my blog entry (http://www.c-sharpcorner.com/Blogs/5951/converting-numbers-to-words-adding-decimal-support.aspx) there's a routine for adding decimal support to a similar program I did for the Indian numbering system which should also work for this US/UK numbering system program. So here you'd do: double d = double.Parse(label1.Text); int i = (int)d; string decimalPart = d.ToString().Split('.')[1]; label1.Text = NumberToText(i, false) + " Point" + DecimalToText(decimalPart);

Posted by Vulpes Apr 01, 2012

Dear Vulpes, Thanks Alot for your efforts and intrest sir its working well ,but how about if the number, include Double Value like :22.1 Best wishes Hani

Posted by hani ahmad Apr 01, 2012

You first need to parse the label's text to an integer: int number = int.Parse(label1.Text). You can then call the NumberToText method and reassign the return value back to the label: label1.Text = NumberToText(number, false);

Posted by Vulpes Mar 31, 2012

please can you give me the way to use this function in Label. with science that is allready number in that label?

Posted by hani ahmad Mar 31, 2012

Jitendra, I'm digging out my version for the Indian number system and will be posting it on your forum thread shortly.

Posted by Vulpes May 04, 2011
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Become a Sponsor