We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Thursday, July 28, 2016

How to convert a number into words in C#

using System;


namespace NumberToWord
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Pleas Enter the Number");
            int i = Convert.ToInt32(Console.ReadLine());
            string result = NumberToString(i);

            Console.WriteLine(result);
            Console.ReadLine();

        }
        public static string NumberToString(int num)
        {
            if (num == 0)
                return "zero";

            if (num < 0)
                return "minus " + NumberToString(Math.Abs(num));

            string words = "";

            if ((num / 1000000) > 0)
            {
                words += NumberToString(num / 1000000) + " million ";
                num %= 1000000;
            }

            if ((num / 1000) > 0)
            {
                words += NumberToString(num / 1000) + " thousand ";
                num %= 1000;
            }

            if ((num / 100) > 0)
            {
                words += NumberToString(num / 100) + " hundred ";
                num %= 100;
            }

            if (num > 0)
            {
                if (words != "")
                    words += "and ";

                var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
                var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

                if (num < 20)
                    words += unitsMap[num];
                else
                {
                    words += tensMap[num / 10];
                    if ((num % 10) > 0)
                        words += "-" + unitsMap[num % 10];
                }
            }

            return words;
        }
    }
}

Output

No comments: