Integer to word conversion

Asked
14 years, 1 month ago

Viewed
50k times

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

abatishchev's user avatar

abatishchev

97.3k85 gold badges297 silver badges432 bronze badges

asked Feb 16, 2009 at 19:35

Malfist's user avatar

1

Currently the best, most robust, library for this is definitely Humanizer. It’s open sourced and available as a nuget:

Console.WriteLine(4567788.ToWords()); // => four million five hundred and sixty-seven thousand seven hundred and eighty-eight

It also has a wide range of tools solving the small problems every application has with strings, enums, DateTimes, TimeSpans and so forth, and supports many different languages.

Console.WriteLine(4567788.ToOrdinalWords().Underscore().Hyphenate().ApplyCase(LetterCasing.AllCaps)); // => FOUR-MILLION-FIVE-HUNDRED-AND-SIXTY-SEVEN-THOUSAND-SEVEN-HUNDRED-AND-EIGHTY-EIGHTH

answered Jun 3, 2014 at 14:03

i3arnon's user avatar

i3arnoni3arnon

112k33 gold badges321 silver badges340 bronze badges

6

if you use the code found in:
converting numbers in to words C#
and you need it for decimal numbers, here is how to do it:

public string DecimalToWords(decimal number)
{
    if (number == 0)
        return "zero";

    if (number < 0)
        return "minus " + DecimalToWords(Math.Abs(number));

    string words = "";

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

    words = NumericToWords(intPortion);
    if (decPortion > 0)
    {
        words += " and ";
        words += NumericToWords(decPortion);
    }
    return words;
}

Community's user avatar

answered Oct 19, 2011 at 23:40

Ruben Carreon's user avatar

1

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.

answered Nov 26, 2013 at 17:46

Hannele's user avatar

HanneleHannele

9,1646 gold badges49 silver badges66 bronze badges

2

In case anyone wants a JavaScript version

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

    var num = this.valueOf();
    if (Math.round(num == 0)) {
        return "zero";
    }
    if (num < 0) {
        var positivenum = Math.abs(num);
        return "minus " + Number(positivenum).numberToWords();
    }
    var words = "";
    if (Math.floor(num / 1000000) > 0) {
        words += Math.floor(num / 1000000).numberToWords() + " million ";
        num = Math.floor(num % 1000000);
    }
    if (Math.floor(num / 1000) > 0) {
        words += Math.floor(num / 1000).numberToWords() + " thousand ";
        num = Math.floor(num % 1000);
    }
    if (Math.floor(num / 100) > 0) {
        words += Math.floor(num / 100).numberToWords() + " hundred ";
        num = Math.floor(num % 100);
    }
    if (Math.floor(num > 0)) {
        if (words != "") {
            words += "and ";
        }
        if (num < 20) {
        words += unitsMap[num];
        }
        else {
            words += tensMap[Math.floor(num / 10)];
            if ((num % 10) > 0) {
                words += "-" + unitsMap[Math.round(num % 10)];
            }
        }
    }
    return words.trim();
}

answered Aug 8, 2014 at 5:38

Elliot Wood's user avatar

Elliot WoodElliot Wood

9581 gold badge9 silver badges29 bronze badges

Here is the spanish version:

        public static string numeroALetras(int number)
    {
        if (number == 0)
            return "cero";

        if (number < 0)
            return "menos " + numeroALetras(Math.Abs(number));

        string words = "";

        if ((number / 1000000) > 0)
        {
            words += numeroALetras(number / 1000000) + " millón ";
            number %= 1000000;
        }

        if ((number / 1000) > 0)
        {
            words += (number / 1000) == 1? "mil ": numeroALetras(number / 1000) + " mil ";
            number %= 1000;
        }
        if ((number / 100) == 1)
        {
            if (number == 100)
                words += "cien";
            else words += (number / 100)> 1? numeroALetras(number / 100) + " ciento ":"ciento ";
            number %= 100;
        }
        if ((number / 100) > 1)
        {
            var hundredMap = new[] {"","", "dosc", "tresc", "cuatroc", "quin", "seisc", "sietec", "ochoc", "novec" };
            if (number > 199)
                words += hundredMap[number/100] + "ientos ";
            else {
                words += numeroALetras(number / 100) + " ientos ";
            }
            number %= 100;
        }

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

            var unitsMap = new[] { "cero", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez", "once", "doce", "trece", "catorce", "quince", "dieciseis", "diecisiete", "dieciocho", "diecinueve", "veinte" };
            var tensMap = new[] { "cero", "diez", "veinti", "treinta", "cuarenta", "cincuenta", "sesenta", "setenta", "ochenta", "noventa" };

            if (number < 21)
                words += unitsMap[number];
            else
            {                    
                words += tensMap[number / 10];
                if ((number % 10) > 0)
                    words += ((number % 10)>2?" y ": "") + unitsMap[number % 10];                    
            }
        }

        return words;
    }

answered Jun 1, 2017 at 15:12

Xtian11's user avatar

Xtian11Xtian11

2,0941 gold badge21 silver badges13 bronze badges

Imports System.Text

Public Class NumberWriter

    Public Shared Function Parse(ByVal Number As String) As String
        If Not AreNumbers(Number) Then Return ""
        Dim TempQueue As New Queue(Of String)
        For Each ItemA As Char In Number.Replace(",", "").Reverse
            TempQueue.Enqueue(ItemA)
        Next
        Dim Blocks As New List(Of String)
        Dim BlockEmpty As New List(Of Boolean)
        Do
            Dim TempBlock As New StringBuilder(3)
            TempBlock.Append(TempQueue.Dequeue)
            If TempQueue.Count > 0 Then
                TempBlock.Append(TempQueue.Dequeue)
                If TempQueue.Count > 0 Then
                    TempBlock.Append(TempQueue.Dequeue)
                End If
            End If
            Blocks.Add(StrReverse(TempBlock.ToString))
            BlockEmpty.Add(TempBlock.ToString = "000")
            If TempQueue.Count < 1 Then Exit Do
        Loop
        Dim ResultStack As New Stack(Of String)
        For int1 As Integer = 0 To Blocks.Count - 1
            ResultStack.Push(ReadBlock(Blocks(int1)) & If(Not int1 = 0, If(Not BlockEmpty(int1), " " & CapitalizeWord(GetPlaceValueSet(int1)) & If(BlockEmpty(int1 - 1), "", ", "), ""), ""))
        Next
        Dim Result1 As String = ""
        Do Until ResultStack.Count < 1
            Result1 &= ResultStack.Pop
        Loop
        Return RemoveGrammarErrors(Result1)
    End Function

    Private Shared Function RemoveGrammarErrors(ByVal Str As String) As String
        Dim tstr As String = Str
        tstr.Replace("  ", " ")
        tstr.Replace(" , ", ", ")
        Return tstr
    End Function

    Private Shared Function AreNumbers(ByVal Str1 As String) As Boolean
        Dim Numbers() As String = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ","}
        For Each ItemA As Char In Str1
            Dim IsN As Boolean = False
            For Each ItemB As String In Numbers
                If ItemA = ItemB Then IsN = True
            Next
            If Not IsN Then
                Return False
            End If
        Next
        Return True
    End Function

    Private Shared Function ReadBlock(ByVal Block As String)
        Select Case Block.Length
            Case 1
                Return ReadSingleDigit(Block)
            Case 2
                Return ReadTwoDigits(Block)
            Case 3
                Return ReadThreeDigits(Block)
            Case Else
                Throw New Exception
        End Select
    End Function

    Private Shared Function ReadThreeDigits(ByVal Digits As String)
        If Digits.Length > 3 Then Throw New ArgumentException("There are too many digits.")
        Dim Result As String = ""
        If Not Digits(0) = "0" Then
            Result &= ReadSingleDigit(Digits(0)) & " Hundred "
        End If
        Result &= ReadTwoDigits(Digits.Substring(1))
        Return Result
    End Function

    Private Shared Function ReadTwoDigits(ByVal Digits As String)
        If Digits.Length > 2 Then Throw New ArgumentException("There are too many digits.")
        Select Case Digits(0)
            Case "0"
                Return ReadSingleDigit(Digits(1))
            Case "1"
                Return ReadTeenNumber(Digits)
            Case Else
                Return ReadFirstInNumberPair(Digits(0)) & If(Digits(1) = "0", "", "-" & ReadSingleDigit(Digits(1)))
        End Select
    End Function

    Private Shared Function ReadSingleDigit(ByVal Digit As String) As String
        If Not Digit.Length = 1 Then Throw New ArgumentException("There must be only one digit and it must be more than zero.")
        Select Case Digit
            Case "0"
                Return ""
            Case "1"
                Return "One"
            Case "2"
                Return "Two"
            Case "3"
                Return "Three"
            Case "4"
                Return "Four"
            Case "5"
                Return "Five"
            Case "6"
                Return "Six"
            Case "7"
                Return "Seven"
            Case "8"
                Return "Eight"
            Case "9"
                Return "Nine"
            Case Else
                Throw New Exception()
        End Select
    End Function

    Private Shared Function ReadTeenNumber(ByVal Num As String) As String
        Select Case Num
            Case "11"
                Return "Eleven"
            Case "12"
                Return "Twelve"
            Case "13"
                Return "Thirteen"
            Case "14"
                Return "Fourteen"
            Case "15"
                Return "Fifteen"
            Case "16"
                Return "Sixteen"
            Case "17"
                Return "Seventeen"
            Case "18"
                Return "Eighteen"
            Case "19"
                Return "Nineteen"
            Case Else
                Throw New Exception()
        End Select
    End Function

    Private Shared Function ReadFirstInNumberPair(ByVal Num As String) As String
        If Not (Num > 1 OrElse Num < 10) Then Throw New ArgumentException("Number must be more than 1 and less than 10")
        Select Case Num
            Case "2"
                Return "Twenty"
            Case "3"
                Return "Thirty"
            Case "4"
                Return "Fourty"
            Case "5"
                Return "Fifty"
            Case "6"
                Return "Sixty"
            Case "7"
                Return "Seventy"
            Case "8"
                Return "Eighty"
            Case "9"
                Return "Ninety"
            Case Else
                Throw New Exception()
        End Select
    End Function

    Private Shared Function CapitalizeWord(ByVal Word As String) As String
        Return Word.Substring(0, 1).ToUpper & Word.Substring(1)
    End Function

    Private Shared Function GetPlaceValueSet(ByVal Num As Byte) As String
        Select Case Num
            Case 0
                Return "" 'Hundreds
            Case 1
                Return "Thousand"
            Case 2
                Return "Million"
            Case 3
                Return "Billion"
            Case 4
                Return "Trillion"
            Case 5
                Return "Quadrillion"
            Case 6
                Return "Quintillion"
            Case 7
                Return "Sextillion"
            Case 8
                Return "Septillion"
            Case 9
                Return "Octillion"
            Case 10
                Return "Nonillion"
            Case 11
                Return "octillion"
            Case 12
                Return "nonillion"
            Case 13
                Return "decillion"
            Case 14
                Return "undecillion"
            Case 15
                Return "dodecillion,"
            Case 16
                Return "tredecillion"
            Case 17
                Return "quattuordecillion"
            Case 18
                Return "quindecillion"
            Case 19
                Return "sexdecillion"
            Case 20
                Return "septendecillion"
            Case 21
                Return "octodecillion"
            Case 22
                Return "novemdecillion"
            Case 23
                Return "vigintillion"
            Case 24
                Return "unvigintillion"
            Case 25
                Return "dovigintillion"
            Case 26
                Return "trevigintillion"
            Case 27
                Return "quattuorvigintillion"
            Case 28
                Return "quinvigintillion"
            Case 29
                Return "sexvigintillion"
            Case 30
                Return "septenvigintillion"
            Case 31
                Return "octovigintillion"
            Case 32
                Return "novemvigintillion"
            Case 33
                Return "trigintillion"
            Case 34
                Return "untrigintillion"
            Case 35
                Return "dotrigintillion"
            Case 36
                Return "tretrigintillion"
            Case 37
                Return "quattuortrigintillion"
            Case 38
                Return "quintrigintillion"
            Case 39
                Return "sextrigintillion"
            Case 40
                Return "septentrigintillion"
            Case 41
                Return "octotrigintillion"
            Case Else
                Throw New Exception
        End Select
    End Function
End Class

Sorry it’s in VB.NET, but it works completely. It is one way. Number to Verbal. Handles numbers up to 123 characters long I believe.

answered Sep 24, 2012 at 6:16

Mitch's user avatar

MitchMitch

573 bronze badges

I actually needed this for an app I’m working on, but wasn’t happy with any of the solutions here. FYI, this solution takes advantage of C# 7.0’s support for local functions. I also used the new digit separator to make the larger numbers more readable.

public static class NumberExtensions
{
    private const string negativeWord = "negative";
    private static readonly Dictionary<ulong, string> _wordMap = new Dictionary<ulong, string>
    {
        [1_000_000_000_000_000_000] = "quintillion",
        [1_000_000_000_000_000] = "quadrillion",
        [1_000_000_000_000] = "trillion",
        [1_000_000_000] = "billion",
        [1_000_000] = "million",
        [1_000] = "thousand",
        [100] = "hundred",
        [90] = "ninety",
        [80] = "eighty",
        [70] = "seventy",
        [60] = "sixty",
        [50] = "fifty",
        [40] = "forty",
        [30] = "thirty",
        [20] = "twenty",
        [19] = "nineteen",
        [18] = "eighteen",
        [17] = "seventeen",
        [16] = "sixteen",
        [15] = "fifteen",
        [14] = "fourteen",
        [13] = "thirteen",
        [12] = "twelve",
        [11] = "eleven",
        [10] = "ten",
        [9] = "nine",
        [8] = "eight",
        [7] = "seven",
        [6] = "six",
        [5] = "five",
        [4] = "four",
        [3] = "three",
        [2] = "two",
        [1] = "one",
        [0] = "zero"
    };

    public static string ToWords(this short num)
    {
        var words = ToWords((ulong)Math.Abs(num));
        return num < 0 ? $"{negativeWord} {words}" : words;
    }

    public static string ToWords(this ushort num)
    {
        return ToWords((ulong)num);
    }

    public static string ToWords(this int num)
    {
        var words = ToWords((ulong)Math.Abs(num));
        return num < 0 ? $"{negativeWord} {words}" : words;
    }

    public static string ToWords(this uint num)
    {
        return ToWords((ulong)num);
    }

    public static string ToWords(this long num)
    {
        var words = ToWords((ulong)Math.Abs(num));
        return num < 0 ? $"{negativeWord} {words}" : words;
    }

    public static string ToWords(this ulong num)
    {
        var sb = new StringBuilder();
        var delimiter = String.Empty;

        void AppendWords(ulong dividend)
        {
            void AppendDelimitedWord(ulong key)
            {
                sb.Append(delimiter);
                sb.Append(_wordMap[key]);
                delimiter = 20 <= key && key < 100 ? "-" : " ";
            }

            if (_wordMap.ContainsKey(dividend))
            {
                AppendDelimitedWord(dividend);
            }
            else
            {
                var divisor = _wordMap.First(m => m.Key <= dividend).Key;
                var quotient = dividend / divisor;
                var remainder = dividend % divisor;

                if (quotient > 0 && divisor >= 100)
                {
                    AppendWords(quotient);
                }

                AppendDelimitedWord(divisor);

                if (remainder > 0)
                {   
                    AppendWords(remainder);
                }
            }
        }

        AppendWords(num);
        return sb.ToString();
    }    
}

The meat is in the last ToWords overload.

answered Jul 8, 2017 at 1:21

Chris Pratt's user avatar

Chris PrattChris Pratt

229k35 gold badges382 silver badges439 bronze badges

1

http://www.exchangecore.com/blog/convert-number-words-c-sharp-console-application/ has some C# script that looks to handle very large numbers and very small decimals.

using System;
using System.Collections.Generic;
using System.Text;

namespace NumWords
{
    class Program
    {
        // PROGRAM HANDLES NEGATIVE AND POSITIVE DOUBLES


        static String NumWordsWrapper(double n)
        {
            string words = "";
            double intPart;
            double decPart = 0;
            if (n == 0)
                return "zero";
            try {
                string[] splitter = n.ToString().Split('.');
                intPart = double.Parse(splitter[0]);
                decPart = double.Parse(splitter[1]);
            } catch {
                intPart = n;
            }

            words = NumWords(intPart);

            if (decPart > 0) {
                if (words != "")
                    words += " and ";
                int counter = decPart.ToString().Length;
                switch (counter) {
                    case 1: words += NumWords(decPart) + " tenths"; break;
                    case 2: words += NumWords(decPart) + " hundredths"; break;
                    case 3: words += NumWords(decPart) + " thousandths"; break;
                    case 4: words += NumWords(decPart) + " ten-thousandths"; break;
                    case 5: words += NumWords(decPart) + " hundred-thousandths"; break;
                    case 6: words += NumWords(decPart) + " millionths"; break;
                    case 7: words += NumWords(decPart) + " ten-millionths"; break;
                }
            }
            return words;
        }

        static String NumWords(double n) //converts double to words
        {
            string[] numbersArr = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
            string[] tensArr = new string[] { "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninty" };
            string[] suffixesArr = new string[] { "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "Quattuordecillion", "Quindecillion", "Sexdecillion", "Septdecillion", "Octodecillion", "Novemdecillion", "Vigintillion" };
            string words = "";

            bool tens = false;

            if (n < 0) {
                words += "negative ";
                n *= -1;
            }

            int power = (suffixesArr.Length + 1) * 3;

            while (power > 3) {
                double pow = Math.Pow(10, power);
                if (n >= pow) {
                    if (n % pow > 0) {
                        words += NumWords(Math.Floor(n / pow)) + " " + suffixesArr[(power / 3) - 1] + ", ";
                    } else if (n % pow == 0) {
                        words += NumWords(Math.Floor(n / pow)) + " " + suffixesArr[(power / 3) - 1];
                    }
                    n %= pow;
                }
                power -= 3;
            }
            if (n >= 1000) {
                if (n % 1000 > 0) words += NumWords(Math.Floor(n / 1000)) + " thousand, ";
                else words += NumWords(Math.Floor(n / 1000)) + " thousand";
                n %= 1000;
            }
            if (0 <= n && n <= 999) {
                if ((int)n / 100 > 0) {
                    words += NumWords(Math.Floor(n / 100)) + " hundred";
                    n %= 100;
                }
                if ((int)n / 10 > 1) {
                    if (words != "")
                        words += " ";
                    words += tensArr[(int)n / 10 - 2];
                    tens = true;
                    n %= 10;
                }

                if (n < 20 && n > 0) {
                    if (words != "" && tens == false)
                        words += " ";
                    words += (tens ? "-" + numbersArr[(int)n - 1] : numbersArr[(int)n - 1]);
                    n -= Math.Floor(n);
                }
            }

            return words;

        }
        static void Main(string[] args)
        {
            Console.Write("Enter a number to convert to words: ");
            Double n = Double.Parse(Console.ReadLine());

            Console.WriteLine("{0}", NumWordsWrapper(n));
        }
    }
}

EDIT: brought code over from blog post

answered Jul 18, 2012 at 17:11

Joe Meyer's user avatar

Joe MeyerJoe Meyer

4,24119 silver badges28 bronze badges

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

answered Oct 20, 2017 at 2:51

Marvin Glenn Lacuna's user avatar

Here is my solution hope it will help you

namespace ConsoleApplication3
{

    class Program
    {


        static void Main(string[] args)
        {

            string s = Console.ReadLine();
            ConvertMyword(int.Parse(s));

            Console.Read();

        }

        static void ConvertMyword(int number)
        {
            int flag = 0;
            int lflag = 0;
            string words = String.Empty;
            string[] places = { "ones", "ten", "hundred", "thousand", "ten thousand", "lacs","tenlacs","crore","tencrore" };
            string rawnumber = number.ToString();
            char[] a = rawnumber.ToCharArray();
            Array.Reverse(a);
            for (int i = a.Length - 1; i >= 0; i--)
            {
                if (i % 2 == 0 && i > 2)
                {
                    if (int.Parse(a[i].ToString()) > 1)
                    {
                        if (int.Parse(a[i - 1].ToString()) == 0)
                        {
                            words = words + getNumberStringty(int.Parse(a[i].ToString())) + " " + places[i - 1] + " ";
                        }
                        else
                        {
                            words = words + getNumberStringty(int.Parse(a[i].ToString())) + " ";
                        }
                    }
                    else if (int.Parse(a[i].ToString()) == 1)
                    {
                        if (int.Parse(a[i - 1].ToString())== 0)
                        {
                            words = words +"Ten" + " ";
                        }
                        else
                        {
                            words = words + getNumberStringteen(int.Parse(a[i - 1].ToString())) + " ";
                        }
                        flag = 1;
                    }
                }
                else
                {
                    if (i == 1 || i == 0)
                    {
                        if (int.Parse(a[i].ToString()) > 1)
                        {
                            words = words + getNumberStringty(int.Parse(a[i].ToString())) + " " + getNumberString(int.Parse(a[0].ToString())) + " ";
                            break;
                        }
                        else if (int.Parse(a[i].ToString()) == 1)
                        {
                            if (int.Parse(a[i - 1].ToString()) == 0)
                            {
                                words = words + "Ten" + " ";
                            }
                            else
                            {
                                words = words + getNumberStringteen(int.Parse(a[i - 1].ToString())) + " ";
                            }

                            break;
                        }
                        else if (int.Parse(a[i - 1].ToString()) != 0)
                        {
                            words = words + getNumberString(int.Parse(a[i - 1].ToString())) + " ";
                            break;
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        if (flag == 0)
                        {
                            for(int l=i;l>=0;l--)
                            {
                                if (int.Parse(a[l].ToString())!=0)
                                {
                                    lflag = 1;
                                }
                            }
                            if (lflag == 1 && int.Parse(a[i].ToString())!=0)
                            {

                                    words = words + getNumberString(int.Parse(a[i].ToString())) + " " + places[i] + " ";
                                    lflag = 0;


                            }
                            else if(lflag == 0)
                            {
                               // words = words + getNumberString(int.Parse(a[i].ToString())) + " " + places[i] + " ";
                                lflag = 0;
                                break;
                            }

                        }
                        else
                        {
                            words = words + " " + places[i] + " ";
                            flag = 0;
                        }

                    }
                }
            }
            Console.WriteLine(words);
        }
        static string getNumberString(int num)
        {
            string Word = String.Empty;
            switch (num)
            {
                case 1:
                    Word = "one";
                    break;
                case 2:
                    Word = "two";
                    break;

                case 3:
                    Word = "three";
                    break;

                case 4:
                    Word = "four";
                    break;

                case 5:
                    Word = "five";
                    break;

                case 6:
                    Word = "six";
                    break;
                case 7:
                    Word = "seven";
                    break;

                case 8:
                    Word = "eight";
                    break;

                case 9:
                    Word = "nine";
                    break;


            }
            return Word;
        }
        static string getNumberStringty(int num)
        {
            string Word = String.Empty;
            switch (num)
            {

                case 2:
                    Word = "twenty";
                    break;

                case 3:
                    Word = "thirty";
                    break;

                case 4:
                    Word = "fourty";
                    break;

                case 5:
                    Word = "fifty";
                    break;

                case 6:
                    Word = "sixty";
                    break;
                case 7:
                    Word = "seventy";
                    break;

                case 8:
                    Word = "eighty";
                    break;

                case 9:
                    Word = "ninty";
                    break;


            }
            return Word;
        }
        static string getNumberStringteen(int num)
        {
            string Word = String.Empty;
            switch (num)
            {
                    case 1:
                    Word = "eleven";
                    break;
                case 2:
                    Word = "tewlve";
                    break;

                case 3:
                    Word = "thirteen";
                    break;

                case 4:
                    Word = "fourteen";
                    break;

                case 5:
                    Word = "fifteen";
                    break;

                case 6:
                    Word = "sixteen";
                    break;
                case 7:
                    Word = "seventeen";
                    break;

                case 8:
                    Word = "eighteen";
                    break;

                case 9:
                    Word = "ninteen";
                    break;


            }
            return Word;
        }
    }

}

Ren's user avatar

Ren

1,1115 gold badges15 silver badges24 bronze badges

answered Jan 17, 2013 at 12:13

Ahmar Husain's user avatar

This class perfectly converts your float or double (till 2 precision).
Just copy and paste in your IDE and see the result.

class ConversionClass
{
    private static Dictionary<int, string> InitialNumbers = new Dictionary<int, string>();
    private static Dictionary<int, string> MultipleOfTen = new Dictionary<int, string>();
    private static Dictionary<int, string> MultipleOfHundered = new Dictionary<int, string>();

    private static void InitializeStatic()
    {
        //InitialNumbers.Add(0, "zero");
        InitialNumbers.Add(1, "one");
        InitialNumbers.Add(2, "two");
        InitialNumbers.Add(3, "three");
        InitialNumbers.Add(4, "four");
        InitialNumbers.Add(5, "five");
        InitialNumbers.Add(6, "six");
        InitialNumbers.Add(7, "seven");
        InitialNumbers.Add(8, "eight");
        InitialNumbers.Add(9, "nine");
        InitialNumbers.Add(10, "ten");
        InitialNumbers.Add(11, "eleven");
        InitialNumbers.Add(12, "tweleve");
        InitialNumbers.Add(13, "thirteen");
        InitialNumbers.Add(14, "fourteen");
        InitialNumbers.Add(15, "fifteen");
        InitialNumbers.Add(16, "sixteen");
        InitialNumbers.Add(17, "seventeen");
        InitialNumbers.Add(18, "eighteen");
        InitialNumbers.Add(19, "nineteen");

        MultipleOfTen.Add(1, "ten");
        MultipleOfTen.Add(2, "twenty");
        MultipleOfTen.Add(3, "thirty");
        MultipleOfTen.Add(4, "fourty");
        MultipleOfTen.Add(5, "fifty");
        MultipleOfTen.Add(6, "sixty");
        MultipleOfTen.Add(7, "seventy");
        MultipleOfTen.Add(8, "eighty");
        MultipleOfTen.Add(9, "ninety");

        MultipleOfHundered.Add(2, "hundred");                      //                100
        MultipleOfHundered.Add(3, "thousand");                     //              1 000
        MultipleOfHundered.Add(4, "thousand");                     //             10 000
        MultipleOfHundered.Add(5, "thousand");                     //            100 000
        MultipleOfHundered.Add(6, "million");                      //          1 000 000
        MultipleOfHundered.Add(7, "million");                      //        100 000 000
        MultipleOfHundered.Add(8, "million");                      //      1 000 000 000
        MultipleOfHundered.Add(9, "billion");                      //  1 000 000 000 000
    }

    public static void Main()
    {
        InitializeStatic();
        Console.WriteLine("Enter number :");
        var userInput = Console.ReadLine();
        double userValue ;
        if (double.TryParse(userInput, out userValue))  // userValue = 193524019.50
        {
            int decimalPortion = (int)userValue;
            //var fractionPortion = Math.Ceiling(((userValue < 1.0) ? userValue : (userValue % Math.Floor(userValue))) * 100);
            int fractionPortion = (int)(userValue * 100) - ((int)userValue * 100);

            int digit; int power;
            StringBuilder numberInText = new StringBuilder();

            while (decimalPortion > 0)
            {
                GetDigitAndPower(decimalPortion, out digit, out power);
                numberInText.Append(ConvertToText(ref decimalPortion, ref digit, ref power));
                if (decimalPortion > 0)
                {
                    decimalPortion = GetReminder(decimalPortion, digit, power);
                }
            }
            numberInText.Append(" point ");
            while (fractionPortion > 0)
            {
                GetDigitAndPower(fractionPortion, out digit, out power);
                numberInText.Append(ConvertToText(ref fractionPortion, ref digit, ref power));
                if (fractionPortion > 0)
                {
                    fractionPortion = GetReminder(fractionPortion, digit, power);
                }
            }

            Console.WriteLine(numberInText.ToString());
        }
        Console.ReadKey();
    }

    private static int GetReminder(int orgValue, int digit, int power)
    {
        int returningValue = orgValue - (digit * (int)Math.Pow(10, power));
        return returningValue;
    }

    private static void GetDigitAndPower(int originalValue, out int digit, out int power)
    {
        for (power = 0, digit = 0; power < 10; power++)
        {
            var divisionFactor = (int)Math.Pow(10, power);
            int operationalValue = (originalValue / divisionFactor);
            if (operationalValue <= 0)
            {
                power = power - 1;
                digit = (int)(originalValue / Math.Pow(10, power));
                break;
            }
        } 
    }

    private static string ConvertToText(ref int orgValue, ref int digit, ref int power)
    {
        string numberToText = string.Empty;

        if (power < 2)
        {
            if (InitialNumbers.ContainsKey(orgValue))
            {
                //This is for number 1 to 19
                numberToText = InitialNumbers[orgValue];
                orgValue = 0;
            }
            else if (MultipleOfTen.ContainsKey(digit))
            {
                //This is for multiple of 10 (20,30,..90)
                numberToText = MultipleOfTen[digit];
            }
        }
        else
        {
            if (power < 4)
            {
                numberToText = string.Format("{0} {1}", InitialNumbers[digit], MultipleOfHundered[power]);
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                int multiplicationFactor = power / 3;
                int innerOrgValue = (int) (orgValue / Math.Pow(10, (multiplicationFactor * 3)));
                digit = innerOrgValue;
                var multiple = MultipleOfHundered[power];
                power = power - ((int)Math.Ceiling(Math.Log10(innerOrgValue)) - 1);

                int innerPower = 0;
                int innerDigit = 0;
                while (innerOrgValue > 0)
                {
                    GetDigitAndPower(innerOrgValue, out innerDigit, out innerPower);
                    var text = ConvertToText(ref innerOrgValue, ref innerDigit, ref innerPower);
                    sb.Append(text);
                    sb.Append(" ");
                    if (innerOrgValue > 0)
                    {
                        innerOrgValue = GetReminder(innerOrgValue, innerDigit, innerPower);
                    }
                }
                sb.Append(multiple);
                numberToText = sb.ToString();

            }
        }

        return numberToText + " ";
    }

}

answered Jun 25, 2015 at 2:43

Aamol's user avatar

AamolAamol

1,1011 gold badge15 silver badges21 bronze badges

2

Though this is kind of old question, I have implemented this functionality with more detailed approach

public static class NumberToWord
    {
        private static readonly Dictionary<long, string> MyDictionary = new Dictionary<long, string>();

        static NumberToWord()
        {
            MyDictionary.Add(1000000000000000, "quadrillion");
            MyDictionary.Add(1000000000000, "trillion");
            MyDictionary.Add(1000000000, "billion");
            MyDictionary.Add(1000000, "million");
            MyDictionary.Add(1000, "thousand");
            MyDictionary.Add(100, "hundread");
            MyDictionary.Add(90, "ninety");
            MyDictionary.Add(80, "eighty");
            MyDictionary.Add(70, "seventy");
            MyDictionary.Add(60, "sixty");
            MyDictionary.Add(50, "fifty");
            MyDictionary.Add(40, "fourty");
            MyDictionary.Add(30, "thirty");
            MyDictionary.Add(20, "twenty");
            MyDictionary.Add(19, "nineteen");
            MyDictionary.Add(18, "eighteen");
            MyDictionary.Add(17, "seventeen");
            MyDictionary.Add(16, "sixteen");
            MyDictionary.Add(15, "fifteen");
            MyDictionary.Add(14, "fourteen");
            MyDictionary.Add(13, "thirteen");
            MyDictionary.Add(12, "twelve");
            MyDictionary.Add(11, "eleven");
            MyDictionary.Add(10, "ten");
            MyDictionary.Add(9, "nine");
            MyDictionary.Add(8, "eight");
            MyDictionary.Add(7, "seven");
            MyDictionary.Add(6, "six");
            MyDictionary.Add(5, "five");
            MyDictionary.Add(4, "four");
            MyDictionary.Add(3, "three");
            MyDictionary.Add(2, "two");
            MyDictionary.Add(1, "one");
            MyDictionary.Add(0, "zero");
        }

        /// <summary>
        /// To the verbal.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string ToVerbal(this int value)
        {
            return ToVerbal((long) value);
        }

        /// <summary>
        /// To the verbal.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string ToVerbal(this long value)
        {
            if (value == 0) return MyDictionary[value];

            if (value < 0)
                return $" negative {ToVerbal(Math.Abs(value))}";

            var builder = new StringBuilder();

            for (var i = 1000000000000000; i >= 1000; i = i/1000)
                value = ConstructWord(value, builder, i);

            value = ConstructWord(value, builder, 100);

            for (var i = 90; i >= 20; i = i - 10)
                value = ConstructWordForTwoDigit(value, builder, i);

            if (MyDictionary.ContainsKey(value))
                builder.AppendFormat("{0}" + MyDictionary[value], builder.Length > 0 
                    ? " " 
                    : string.Empty);

            return builder.ToString();
        }

        private static long ConstructWord(long value, StringBuilder builder, long key)
        {
            if (value >= key)
            {
                var unit = (int) (value/key);
                value -= unit*key;
                builder.AppendFormat(" {0} {1} " + MyDictionary[key], builder.Length > 0
                    ? ", "
                    : string.Empty, ToVerbal(unit));
            }
            return value;
        }
        private static long ConstructWordForTwoDigit(long value, StringBuilder builder, long key)
        {
            if (value >= key)
            {
                value -= key;
                builder.AppendFormat(" {0} " + MyDictionary[key], builder.Length > 0
                    ? " "
                    : string.Empty);
            }
            return value;
        } 
    }

FYI: i have user string interpolation which is only available in 4.6.1

answered Nov 23, 2016 at 14:38

HaBo's user avatar

HaBoHaBo

13.9k36 gold badges113 silver badges205 bronze badges

Solution that takes up less code.

The most important part is only couple lines:

static Func<long, string> remainder = t => t > 0 ? " " + ToEN(t) : "";

public static string ToEN(this long val, double d = 20, long th = 20)
{
    switch ((long)d)
    {
        case 20:   return val >= d ? ToEN(val, 1e2)             : en[val];
        case 100:  return val >= d ? ToEN(val, 1e3, 100)        : en[val / 10 * 10] + remainder(val % 10);
        default:   return val >= d ? ToEN(val, d * 1e3,(long)d) : ToEN(val / th) + " " + en[th] + remainder(val % th);
    }
}

Full code is available here https://dotnetfiddle.net/wjr4hF

answered Dec 1, 2016 at 15:07

Rustem Mustafin's user avatar

Rustem MustafinRustem Mustafin

9591 gold badge11 silver badges23 bronze badges

1

The following C# console app code will give accepts a monetary value in numbers up to 2 decimals and prints it in English. You can use it as a reference to achieve your results.

   namespace ConsoleApplication2
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    class Program
    {
       static void Main(string[] args)
        {
            bool repeat = true;
            while (repeat)
            {
                string inputMonetaryValueInNumberic = string.Empty;
                string centPart = string.Empty;
                string dollarPart = string.Empty;
                Console.Write("nEnter the monetary value : ");
                inputMonetaryValueInNumberic = Console.ReadLine();
                inputMonetaryValueInNumberic = inputMonetaryValueInNumberic.TrimStart('0');

                if (ValidateInput(inputMonetaryValueInNumberic))
                {

                    if (inputMonetaryValueInNumberic.Contains('.'))
                    {
                        centPart = ProcessCents(inputMonetaryValueInNumberic.Substring(inputMonetaryValueInNumberic.IndexOf(".") + 1));
                        dollarPart = ProcessDollar(inputMonetaryValueInNumberic.Substring(0, inputMonetaryValueInNumberic.IndexOf(".")));
                    }
                    else
                    {
                        dollarPart = ProcessDollar(inputMonetaryValueInNumberic);
                    }
                    centPart = string.IsNullOrWhiteSpace(centPart) ? string.Empty : " and " + centPart;
                    Console.WriteLine(string.Format("nn{0}{1}", dollarPart, centPart));
                }
                else
                {
                    Console.WriteLine("Invalid Input..");
                }

                Console.WriteLine("nnPress any key to continue or Escape of close : ");
                var loop = Console.ReadKey();
                repeat = !loop.Key.ToString().Contains("Escape");
                Console.Clear();
            }

        }

        private static string ProcessCents(string cents)
        {
            string english = string.Empty;
            string dig3 = Process3Digit(cents);
            if (!string.IsNullOrWhiteSpace(dig3))
            {
                dig3 = string.Format("{0} {1}", dig3, GetSections(0));
            }
            english = dig3 + english;
            return english;
        }
        private static string ProcessDollar(string dollar)
        {
            string english = string.Empty;
            foreach (var item in Get3DigitList(dollar))
            {
                string dig3 = Process3Digit(item.Value);
                if (!string.IsNullOrWhiteSpace(dig3))
                {
                    dig3 = string.Format("{0} {1}", dig3, GetSections(item.Key));
                }
                english = dig3 + english;
            }
            return english;
        }
        private static string Process3Digit(string digit3)
        {
            string result = string.Empty;
            if (Convert.ToInt32(digit3) != 0)
            {
                int place = 0;
                Stack<string> monetaryValue = new Stack<string>();
                for (int i = digit3.Length - 1; i >= 0; i--)
                {
                    place += 1;
                    string stringValue = string.Empty;
                    switch (place)
                    {
                        case 1:
                            stringValue = GetOnes(digit3[i].ToString());
                            break;
                        case 2:
                            int tens = Convert.ToInt32(digit3[i]);
                            if (tens == 1)
                            {
                                if (monetaryValue.Count > 0)
                                {
                                    monetaryValue.Pop();
                                }
                                stringValue = GetTens((digit3[i].ToString() + digit3[i + 1].ToString()));
                            }
                            else
                            {
                                stringValue = GetTens(digit3[i].ToString());
                            }
                            break;
                        case 3:
                            stringValue = GetOnes(digit3[i].ToString());
                            if (!string.IsNullOrWhiteSpace(stringValue))
                            {
                                string postFixWith = " Hundred";
                                if (monetaryValue.Count > 0)
                                {
                                    postFixWith = postFixWith + " And";
                                }
                                stringValue += postFixWith;
                            }
                            break;
                    }
                    if (!string.IsNullOrWhiteSpace(stringValue))
                        monetaryValue.Push(stringValue);
                }
                while (monetaryValue.Count > 0)
                {
                    result += " " + monetaryValue.Pop().ToString().Trim();
                }
            }
            return result;
        }
        private static Dictionary<int, string> Get3DigitList(string monetaryValueInNumberic)
        {
            Dictionary<int, string> hundredsStack = new Dictionary<int, string>();
            int counter = 0;
            while (monetaryValueInNumberic.Length >= 3)
            {
                string digit3 = monetaryValueInNumberic.Substring(monetaryValueInNumberic.Length - 3, 3);
                monetaryValueInNumberic = monetaryValueInNumberic.Substring(0, monetaryValueInNumberic.Length - 3);
                hundredsStack.Add(++counter, digit3);
            }
            if (monetaryValueInNumberic.Length != 0)
                hundredsStack.Add(++counter, monetaryValueInNumberic);
            return hundredsStack;
        }
        private static string GetTens(string tensPlaceValue)
        {
            string englishEquvalent = string.Empty;
            int value = Convert.ToInt32(tensPlaceValue);
            Dictionary<int, string> tens = new Dictionary<int, string>();
            tens.Add(2, "Twenty");
            tens.Add(3, "Thirty");
            tens.Add(4, "Forty");
            tens.Add(5, "Fifty");
            tens.Add(6, "Sixty");
            tens.Add(7, "Seventy");
            tens.Add(8, "Eighty");
            tens.Add(9, "Ninty");
            tens.Add(10, "Ten");
            tens.Add(11, "Eleven");
            tens.Add(12, "Twelve");
            tens.Add(13, "Thrteen");
            tens.Add(14, "Fourteen");
            tens.Add(15, "Fifteen");
            tens.Add(16, "Sixteen");
            tens.Add(17, "Seventeen");
            tens.Add(18, "Eighteen");
            tens.Add(19, "Ninteen");
            if (tens.ContainsKey(value))
            {
                englishEquvalent = tens[value];
            }

            return englishEquvalent;

        }
        private static string GetOnes(string onesPlaceValue)
        {
            int value = Convert.ToInt32(onesPlaceValue);
            string englishEquvalent = string.Empty;
            Dictionary<int, string> ones = new Dictionary<int, string>();
            ones.Add(1, " One");
            ones.Add(2, " Two");
            ones.Add(3, " Three");
            ones.Add(4, " Four");
            ones.Add(5, " Five");
            ones.Add(6, " Six");
            ones.Add(7, " Seven");
            ones.Add(8, " Eight");
            ones.Add(9, " Nine");

            if (ones.ContainsKey(value))
            {
                englishEquvalent = ones[value];
            }

            return englishEquvalent;
        }
        private static string GetSections(int section)
        {
            string sectionName = string.Empty;
            switch (section)
            {
                case 0:
                    sectionName = "Cents";
                    break;
                case 1:
                    sectionName = "Dollars";
                    break;
                case 2:
                    sectionName = "Thousand";
                    break;
                case 3:
                    sectionName = "Million";
                    break;
                case 4:
                    sectionName = "Billion";
                    break;
                case 5:
                    sectionName = "Trillion";
                    break;
                case 6:
                    sectionName = "Zillion";
                    break;
            }
            return sectionName;
        }
        private static bool ValidateInput(string input)
        {
            return Regex.IsMatch(input, "[0-9]{1,18}(\.[0-9]{1,2})?"))
        }
    }
}

answered Mar 22, 2017 at 1:23

Santhosh's user avatar

SanthoshSanthosh

7317 silver badges19 bronze badges

1

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
}

answered Apr 4, 2022 at 18:31

Mohsen Alyafei's user avatar

Mohsen AlyafeiMohsen Alyafei

4,4923 gold badges28 silver badges42 bronze badges

What is a integers to words converter?

learn more about this tool

With this browser-based utility, you can convert regular integers with digits into English text. You can load as many integers in the input as you need (each entered on a new line) and in the output, the utility will return them written in words as they are pronounced. Each integer can be pronounced in two ways: as a cardinal or as an ordinal value. For example, the integer «3» can be written as «three» (cardinal value) or as «third» (ordinal value). Similarly, negative integers, such as the value «-45» can be written as a cardinal «minus forty-five» or as an ordinal «minus forty-fifth». You can switch between the cardinal and ordinal modes in the options above. Additionally, you can activate the automatic integer type detection mode. In this mode, the application analyses the input integer and chooses the cardinal or ordinal mode on its own. For example, if the entered integer is «1» then it gets rewritten into «one» but if the integer is «1st», then it prints «first». A hidden extra feature of this app is the currency-to-words mode. It recognizes the abbreviations and symbols of world’s most popular banknotes and coins, such as the euro (€), dollar ($), franc (Fr.), rupee (₹), yen (¥), and cent (¢), and if they are present in the input, this mode is switched on. Just like with integers, money can also be turned into cardinal money, for example, «$100» becomes «one hundred dollars», or ordinal money, for example, «$100th» becomes «one hundredth dollar», or the program can automatically determine the money type by checking if it ends with «-st», «-nd», «-rd», or «-th». There are also three additional radio options for choosing the case of output words. You can switch between small letter mode (lowercase), capital letter mode (uppercase), or capitalizing the first letters of each line (sentence case). Integerabulous!

Write code to convert a given number into words. For example, if “1234” is given as input, the output should be “one thousand two hundred thirty-four”.

Following is the implementation for the same. The code supports numbers up to 4 digits, i.e., numbers from 0 to 9999. Idea is to create arrays that store individual parts of output strings. One array is used for single digits, one for numbers from 10 to 19, one for 20, 30, 40, 50, .. etc, and one for powers of 10. 
The given number is divided into two parts: the first two digits and the last two digits, and the two parts are printed separately. 

C++

#include <bits/stdc++.h>

using namespace std;

void convert_to_words(char* num)

{

    int len = strlen(

        num);

    if (len == 0) {

        fprintf(stderr, "empty stringn");

        return;

    }

    if (len > 4) {

        fprintf(stderr,

                "Length more than 4 is not supportedn");

        return;

    }

    char* single_digits[]

        = { "zero", "one", "two",   "three", "four",

            "five", "six", "seven", "eight", "nine" };

    char* two_digits[]

        = { "",          "ten",      "eleven""twelve",

            "thirteen""fourteen", "fifteen", "sixteen",

            "seventeen", "eighteen", "nineteen" };

    char* tens_multiple[] = { "",       "",        "twenty",

                              "thirty", "forty",   "fifty",

                              "sixty""seventy", "eighty",

                              "ninety" };

    char* tens_power[] = { "hundred", "thousand" };

    cout << "n" << num << ": ";

    if (len == 1) {

        cout << single_digits[*num - '0'] << "n";

        return;

    }

    while (*num != '') {

        if (len >= 3) {

            if (*num - '0' != 0) {

                cout << single_digits[*num - '0'] << " ";

                cout << tens_power[len - 3]

                     << " ";

            }

            --len;

        }

        else {

            if (*num == '1') {

                int sum = *num - '0' + *(num + 1) - '0';

                cout << two_digits[sum] << "n";

                return;

            }

            else if (*num == '2' && *(num + 1) == '0') {

                cout << "twentyn";

                return;

            }

            else {

                int i = *num - '0';

                string tm = i ? tens_multiple[i] : "";

                cout << tm << " ";

                ++num;

                if (*num != '0')

                    cout << single_digits[*num - '0']

                         << " ";

            }

        }

        ++num;

    }

}

int main()

{

    convert_to_words("9923");

    convert_to_words("523");

    convert_to_words("89");

    convert_to_words("8");

    return 0;

}

C

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

void convert_to_words(char* num)

{

    int len = strlen(

        num);

    if (len == 0) {

        fprintf(stderr, "empty stringn");

        return;

    }

    if (len > 4) {

        fprintf(stderr,

                "Length more than 4 is not supportedn");

        return;

    }

    char* single_digits[]

        = { "zero", "one", "two",   "three", "four",

            "five", "six", "seven", "eight", "nine" };

    char* two_digits[]

        = { "",          "ten",      "eleven""twelve",

            "thirteen""fourteen", "fifteen", "sixteen",

            "seventeen", "eighteen", "nineteen" };

    char* tens_multiple[] = { "",       "",        "twenty",

                              "thirty", "forty",   "fifty",

                              "sixty""seventy", "eighty",

                              "ninety" };

    char* tens_power[] = { "hundred", "thousand" };

    printf("n%s: ", num);

    if (len == 1) {

        printf("%sn", single_digits[*num - '0']);

        return;

    }

    while (*num != '') {

        if (len >= 3) {

            if (*num - '0' != 0) {

                printf("%s ", single_digits[*num - '0']);

                printf("%s ",

                       tens_power[len - 3]);

            }

            --len;

        }

        else {

            if (*num == '1') {

                int sum = *num - '0' + *(num + 1) - '0';

                printf("%sn", two_digits[sum]);

                return;

            }

            else if (*num == '2' && *(num + 1) == '0') {

                printf("twentyn");

                return;

            }

            else {

                int i = *num - '0';

                printf("%s ", i ? tens_multiple[i] : "");

                ++num;

                if (*num != '0')

                    printf("%s ",

                           single_digits[*num - '0']);

            }

        }

        ++num;

    }

}

int main(void)

{

    convert_to_words("9923");

    convert_to_words("523");

    convert_to_words("89");

    convert_to_words("8");

    return 0;

}

Java

class GFG {

    static void convert_to_words(char[] num)

    {

        int len = num.length;

        if (len == 0) {

            System.out.println("empty string");

            return;

        }

        if (len > 4) {

            System.out.println(

                "Length more than 4 is not supported");

            return;

        }

        String[] single_digits = new String[] {

            "zero", "one", "two",   "three", "four",

            "five", "six", "seven", "eight", "nine"

        };

        String[] two_digits = new String[] {

            "",          "ten",      "eleven""twelve",

            "thirteen""fourteen", "fifteen", "sixteen",

            "seventeen", "eighteen", "nineteen"

        };

        String[] tens_multiple = new String[] {

            "",      "",      "twenty""thirty", "forty",

            "fifty", "sixty", "seventy", "eighty", "ninety"

        };

        String[] tens_power

            = new String[] { "hundred", "thousand" };

        System.out.print(String.valueOf(num) + ": ");

        if (len == 1) {

            System.out.println(single_digits[num[0] - '0']);

            return;

        }

        int x = 0;

        while (x < num.length) {

            if (len >= 3) {

                if (num[x] - '0' != 0) {

                    System.out.print(

                        single_digits[num[x] - '0'] + " ");

                    System.out.print(tens_power[len - 3]

                                     + " ");

                }

                --len;

            }

            else {

                if (num[x] - '0' == 1) {

                    int sum

                        = num[x] - '0' + num[x + 1] - '0';

                    System.out.println(two_digits[sum]);

                    return;

                }

                else if (num[x] - '0' == 2

                         && num[x + 1] - '0' == 0) {

                    System.out.println("twenty");

                    return;

                }

                else {

                    int i = (num[x] - '0');

                    if (i > 0)

                        System.out.print(tens_multiple[i]

                                         + " ");

                    else

                        System.out.print("");

                    ++x;

                    if (num[x] - '0' != 0)

                        System.out.println(

                            single_digits[num[x] - '0']);

                }

            }

            ++x;

        }

    }

    public static void main(String[] args)

    {

        convert_to_words("9923".toCharArray());

        convert_to_words("523".toCharArray());

        convert_to_words("89".toCharArray());

        convert_to_words("8".toCharArray());

    }

}

Python3

def convert_to_words(num):

    l = len(num)

    if (l == 0):

        print("empty string")

        return

    if (l > 4):

        print("Length more than 4 is not supported")

        return

    single_digits = ["zero", "one", "two", "three",

                     "four", "five", "six", "seven",

                     "eight", "nine"]

    two_digits = ["", "ten", "eleven", "twelve",

                  "thirteen", "fourteen", "fifteen",

                  "sixteen", "seventeen", "eighteen",

                  "nineteen"]

    tens_multiple = ["", "", "twenty", "thirty", "forty",

                     "fifty", "sixty", "seventy", "eighty",

                     "ninety"]

    tens_power = ["hundred", "thousand"]

    print(num, ":", end=" ")

    if (l == 1):

        print(single_digits[ord(num[0]) - 48])

        return

    x = 0

    while (x < len(num)):

        if (l >= 3):

            if (ord(num[x]) - 48 != 0):

                print(single_digits[ord(num[x]) - 48],

                      end=" ")

                print(tens_power[l - 3], end=" ")

            l -= 1

        else:

            if (ord(num[x]) - 48 == 1):

                sum = (ord(num[x]) - 48 +

                       ord(num[x+1]) - 48)

                print(two_digits[sum])

                return

            elif (ord(num[x]) - 48 == 2 and

                  ord(num[x + 1]) - 48 == 0):

                print("twenty")

                return

            else:

                i = ord(num[x]) - 48

                if(i > 0):

                    print(tens_multiple[i], end=" ")

                else:

                    print("", end="")

                x += 1

                if(ord(num[x]) - 48 != 0):

                    print(single_digits[ord(num[x]) - 48])

        x += 1

convert_to_words("9923")

convert_to_words("523")

convert_to_words("89")

convert_to_words("8")

C#

using System;

class GFG {

    static void convert_to_words(char[] num)

    {

        int len = num.Length;

        if (len == 0) {

            Console.WriteLine("empty string");

            return;

        }

        if (len > 4) {

            Console.WriteLine("Length more than "

                              + "4 is not supported");

            return;

        }

        string[] single_digits = new string[] {

            "zero", "one", "two",   "three", "four",

            "five", "six", "seven", "eight", "nine"

        };

        string[] two_digits = new string[] {

            "",          "ten",      "eleven""twelve",

            "thirteen""fourteen", "fifteen", "sixteen",

            "seventeen", "eighteen", "nineteen"

        };

        string[] tens_multiple = new string[] {

            "",      "",      "twenty""thirty", "forty",

            "fifty", "sixty", "seventy", "eighty", "ninety"

        };

        string[] tens_power

            = new string[] { "hundred", "thousand" };

        Console.Write((new string(num)) + ": ");

        if (len == 1) {

            Console.WriteLine(single_digits[num[0] - '0']);

            return;

        }

        int x = 0;

        while (x < num.Length) {

            if (len >= 3) {

                if (num[x] - '0' != 0) {

                    Console.Write(

                        single_digits[num[x] - '0'] + " ");

                    Console.Write(tens_power[len - 3]

                                  + " ");

                }

                --len;

            }

            else {

                if (num[x] - '0' == 1) {

                    int sum = num[x] - '0' + num[x + 1] - '0';

                    Console.WriteLine(two_digits[sum]);

                    return;

                }

                else if (num[x] - '0' == 2

                         && num[x + 1] - '0' == 0) {

                    Console.WriteLine("twenty");

                    return;

                }

                else {

                    int i = (num[x] - '0');

                    if (i > 0)

                        Console.Write(tens_multiple[i]

                                      + " ");

                    else

                        Console.Write("");

                    ++x;

                    if (num[x] - '0' != 0)

                        Console.WriteLine(

                            single_digits[num[x] - '0']);

                }

            }

            ++x;

        }

    }

    public static void Main()

    {

        convert_to_words("9923".ToCharArray());

        convert_to_words("523".ToCharArray());

        convert_to_words("89".ToCharArray());

        convert_to_words("8".ToCharArray());

    }

}

PHP

<?php

function convert_to_words($num)

{

    $len = strlen($num); 

    if ($len == 0) 

    {

        echo "empty stringn";

        return;

    }

    if ($len > 4) 

    {

        echo "Length more than 4 "

               "is not supportedn";

        return;

    }

    $single_digits = array("zero", "one", "two"

                           "three", "four", "five"

                           "six", "seven", "eight"

                                           "nine");

    $two_digits = array("", "ten", "eleven", "twelve"

                        "thirteen", "fourteen", "fifteen"

                        "sixteen", "seventeen", "eighteen"

                                               "nineteen");

    $tens_multiple = array("", "", "twenty", "thirty"

                           "forty", "fifty", "sixty"

                           "seventy", "eighty", "ninety");

    $tens_power = array("hundred", "thousand");

    echo $num.": ";

    if ($len == 1) 

    {

        echo $single_digits[$num[0] - '0'] . " n";

        return;

    }

    $x = 0;

    while ($x < strlen($num)) 

    {

        if ($len >= 3)

        {

            if ($num[$x]-'0' != 0)

            {

                echo $single_digits[$num[$x] - '0'] . " ";

                echo $tens_power[$len - 3] . " "

            }

            --$len;

        }

        else 

        {

            if ($num[$x] - '0' == 1) 

            {

                $sum = $num[$x] - '0'

                       $num[$x] - '0';

                echo $two_digits[$sum] . " n";

                return;

            }

            else if ($num[$x] - '0' == 2 && 

                     $num[$x + 1] - '0' == 0)

            {

                echo "twentyn";

                return;

            }

            else 

            {

                $i = $num[$x] - '0';

                if($i > 0)

                echo $tens_multiple[$i] . " ";

                else

                echo "";

                ++$x;

                if ($num[$x] - '0' != 0)

                    echo $single_digits[$num[$x] - 

                                     '0'] . " n";

            }

        }

        ++$x;

    }

}

convert_to_words("9923");

convert_to_words("523");

convert_to_words("89");

convert_to_words("8");

?>

Javascript

<script>

function convert_to_words(num){

    let l = num.length

    if (l == 0){

        document.write("empty string","</br>")

        return

    }

    if (l > 4){

        document.write("Length more than 4 is not supported","</br>")

        return

    }

    let single_digits = ["zero", "one", "two", "three",

                     "four", "five", "six", "seven",

                     "eight", "nine"]

    let two_digits = ["", "ten", "eleven", "twelve",

                  "thirteen", "fourteen", "fifteen",

                  "sixteen", "seventeen", "eighteen",

                  "nineteen"]

    let tens_multiple = ["", "", "twenty", "thirty", "forty",

                     "fifty", "sixty", "seventy", "eighty",

                     "ninety"]

    let tens_power = ["hundred", "thousand"]

    document.write(num, ":"," ")

    if (l == 1){

        document.write(single_digits[num.charCodeAt(0) - 48],"</br>")

        return

    }

    let x = 0

    while (x < num.length){

        if (l >= 3){

            if (num.charCodeAt(x) - 48 != 0){

                document.write(single_digits[num.charCodeAt(x) - 48]," ")

                document.write(tens_power[l - 3]," ")

            }

            l -= 1

        }

        else{

            if (num.charCodeAt(x) - 48 == 1){

                sum = (num.charCodeAt(x) - 48 + num.charCodeAt(x+1) - 48)

                document.write(two_digits[sum],"</br>")

                return

            }

            else if (num.charCodeAt(x) - 48 == 2 &&

                  num.charCodeAt(x + 1) - 48 == 0){

                document.write("twenty","</br>")

                return

            }

            else{

                i = num.charCodeAt(x) - 48

                if(i > 0)

                    document.write(tens_multiple[i], end=" ")

                else

                    document.write("", end="")

                x += 1

                if(num.charCodeAt(x) - 48 != 0)

                    document.write(single_digits[num.charCodeAt(x) - 48],"</br>")

            }

        }

        x += 1

    }

}

convert_to_words("9923")

convert_to_words("523")

convert_to_words("89")

convert_to_words("8")

</script>

Output

9923: nine thousand nine hundred twenty three 
523: five hundred twenty three 
89: eighty nine 
8: eight

Time Complexity: O(N) [N is the length of the string]
Auxiliary Space: O(1)

This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Approach 2: The following code supports numbers up to 15 digits, i.e., numbers from 0 to trillions. The code prints according to the western number system.

Below is the implementation:

C++

#include <bits/stdc++.h>

using namespace std;

string numberToWords(long long int n)

{

    long long int limit = 1000000000000, curr_hun, t = 0;

    if (n == 0)

        return ("Zero");

    string multiplier[] = { "", "Trillion", "Billion",

                            "Million", "Thousand" };

    string first_twenty[] = {

        "",        "One",       "Two",      "Three",

        "Four",    "Five",      "Six",      "Seven",

        "Eight",   "Nine",      "Ten",      "Eleven",

        "Twelve""Thirteen""Fourteen", "Fifteen",

        "Sixteen", "Seventeen", "Eighteen", "Nineteen"

    };

    string tens[]

        = { "",      "Twenty""Thirty", "Forty", "Fifty",

            "Sixty", "Seventy", "Eighty", "Ninety" };

    if (n < 20)

        return (first_twenty[n]);

    string answer = "";

    for (long long int i = n; i > 0;

         i %= limit, limit /= 1000) {

        curr_hun = i / limit;

        while (curr_hun == 0) {

            i %= limit;

            limit /= 1000;

            curr_hun = i / limit;

            ++t;

        }

        if (curr_hun > 99)

            answer += (first_twenty[curr_hun / 100]

                       + " Hundred ");

        curr_hun = curr_hun % 100;

        if (curr_hun > 0 && curr_hun < 20)

            answer += (first_twenty[curr_hun] + " ");

        else if (curr_hun % 10 == 0 && curr_hun != 0)

            answer += (tens[curr_hun / 10 - 1] + " ");

        else if (curr_hun > 20 && curr_hun < 100)

            answer += (tens[curr_hun / 10 - 1] + " "

                       + first_twenty[curr_hun % 10] + " ");

        if (t < 4)

            answer += (multiplier[++t] + " ");

    }

    return (answer);

}

int main()

{

    long long int n = 36;

    cout << numberToWords(n) << 'n';

    n = 123456789;

    cout << numberToWords(n) << 'n';

    n = 10101010110001;

    cout << numberToWords(n) << 'n';

    n = 999999999;

    cout << numberToWords(n) << 'n';

    return 0;

}

Java

public class GFG {

    static String numberToWords(long n)

    {

        long limit = 1000000000000L, curr_hun, t = 0;

        if (n == 0)

            return ("Zero");

        String multiplier[] = { "", "Trillion", "Billion",

                                "Million", "Thousand" };

        String first_twenty[] = {

            "",        "One",       "Two",      "Three",

            "Four",    "Five",      "Six",      "Seven",

            "Eight",   "Nine",      "Ten",      "Eleven",

            "Twelve""Thirteen""Fourteen", "Fifteen",

            "Sixteen", "Seventeen", "Eighteen", "Nineteen"

        };

        String tens[] = { "",        "Twenty", "Thirty",

                          "Forty",   "Fifty""Sixty",

                          "Seventy", "Eighty", "Ninety" };

        if (n < 20L)

            return (first_twenty[(int)n]);

        String answer = "";

        for (long i = n; i > 0; i %= limit, limit /= 1000) {

            curr_hun = i / limit;

            while (curr_hun == 0) {

                i %= limit;

                limit /= 1000;

                curr_hun = i / limit;

                ++t;

            }

            if (curr_hun > 99)

                answer += (first_twenty[(int)curr_hun / 100]

                           + " Hundred ");

            curr_hun = curr_hun % 100;

            if (curr_hun > 0 && curr_hun < 20)

                answer

                    += (first_twenty[(int)curr_hun] + " ");

            else if (curr_hun % 10 == 0 && curr_hun != 0)

                answer

                    += (tens[(int)curr_hun / 10 - 1] + " ");

            else if (curr_hun > 20 && curr_hun < 100)

                answer

                    += (tens[(int)curr_hun / 10 - 1] + " "

                        + first_twenty[(int)curr_hun % 10]

                        + " ");

            if (t < 4)

                answer += (multiplier[(int)++t] + " ");

        }

        return (answer);

    }

    public static void main(String args[])

    {

        long n = 36L;

        System.out.println(numberToWords(n));

        n = 123456789;

        System.out.println(numberToWords(n));

        n = 10101010110001L;

        System.out.println(numberToWords(n));

        n = 999999999;

        System.out.println(numberToWords(n));

    }

}

Python

def numberToWords(n):

    limit, t = 1000000000000, 0

    if (n == 0):

        print("zero")

        return

    multiplier = ["", "Trillion", "Billion", "Million", "Thousand"]

    first_twenty = ["", "One", "Two",

                    "Three", "Four", "Five",

                    "Six", "Seven", "Eight",

                    "Nine", "Ten", "Eleven",

                    "Twelve", "Thirteen", "Fourteen",

                    "Fifteen", "Sixteen", "Seventeen",

                    "Eighteen", "Nineteen"]

    tens = ["", "Twenty", "Thirty", "Forty", "Fifty",

            "Sixty", "Seventy", "Eighty", "Ninety"]

    if (n < 20):

        print(first_twenty[n])

        return

    answer = ""

    i = n

    while(i > 0):

        curr_hun = i // limit

        while (curr_hun == 0):

            i %= limit

            limit /= 1000

            curr_hun = i // limit

            t += 1

        if (curr_hun > 99):

            answer += (first_twenty[curr_hun // 100] + " tensundred ")

        curr_hun = curr_hun % 100

        if (curr_hun > 0 and curr_hun < 20):

            answer += (first_twenty[curr_hun] + " ")

        elif (curr_hun % 10 == 0 and curr_hun != 0):

            answer += (tens[(curr_hun//10) - 1] + " ")

        elif (curr_hun > 19 and curr_hun < 100):

            answer += (tens[(curr_hun//10) - 1] + " " +

                       first_twenty[curr_hun % 10] + " ")

        if (t < 4):

            answer += (multiplier[t] + " ")

        i = i % limit

        limit = limit // 1000

    print(answer)

n = 36

numberToWords(n)

n = 123456789

numberToWords(n)

n = 10101010110001

numberToWords(n)

n = 999999999

numberToWords(n)

C#

using System;

public class numtowords

{

    public static String numberToWords(long n)

    {

        var limit = 1000000000000L;

        long curr_hun;

        var t = 0;

        if (n == 0)

        {

            return ("Zero");

        }

        String[] multiplier = {"", "Trillion", "Billion", "Million", "Thousand"};

        String[] first_twenty = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};

        String[] tens = {"", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};

        if (n < 20L)

        {

            return (first_twenty[(int)n]);

        }

        var answer = "";

        for (long i = n; i > 0;

        i %= limit,

        limit /= 1000)

        {

            curr_hun = i / limit;

            while (curr_hun == 0)

            {

                i %= limit;

                limit /= 1000;

                curr_hun = i / limit;

                ++t;

            }

            if (curr_hun > 99)

            {

                answer += (first_twenty[(int)((int)curr_hun / 100)] + " Hundred ");

            }

            curr_hun = curr_hun % 100;

            if (curr_hun > 0 && curr_hun < 20)

            {

                answer += (first_twenty[(int)curr_hun] + " ");

            }

            else if (curr_hun % 10 == 0 && curr_hun != 0)

            {

                answer += (tens[(int)((int)curr_hun / 10) - 1] + " ");

            }

            else if (curr_hun > 20 && curr_hun < 100)

            {

                answer += (tens[(int)((int)curr_hun / 10) - 1] + " " + first_twenty[(int)curr_hun % 10] + " ");

            }

            if (t < 4)

            {

                answer += (multiplier[(int)++t] + " ");

            }

        }

        return (answer);

    }

    public static void Main(String[] args)

    {

        var n = 36L;

        Console.WriteLine(numtowords.numberToWords(n));

        n = 123456789;

        Console.WriteLine(numtowords.numberToWords(n));

        n = 10101010110001L;

        Console.WriteLine(numtowords.numberToWords(n));

        n = 999999999;

        Console.WriteLine(numtowords.numberToWords(n));

    }

}

Javascript

function numberToWords(n)

{

    let limit = 1000000000000, t = 0

    if (n == 0)

    {

        console.log("zero")

        return

    }

    let multiplier = ["", "Trillion", "Billion", "Million", "Thousand"]

    let first_twenty = ["", "One", "Two",

                    "Three", "Four", "Five",

                    "Six", "Seven", "Eight",

                    "Nine", "Ten", "Eleven",

                    "Twelve", "Thirteen", "Fourteen",

                    "Fifteen", "Sixteen", "Seventeen",

                    "Eighteen", "Nineteen"]

    let tens = ["", "Twenty", "Thirty", "Forty", "Fifty",

            "Sixty", "Seventy", "Eighty", "Ninety"]

    if (n < 20)

    {

        console.log(first_twenty[n])

        return

    }

    let answer = ""

    let i = n

    while(i > 0)

    {

        let curr_hun = Math.floor(i / limit)

        while (curr_hun == 0)

        {

            i %= limit

            limit /= 1000

            curr_hun = Math.floor(i / limit)

            t += 1

        }

        let flr = Math.floor(curr_hun / 100);

        if (curr_hun > 99)

            answer += (first_twenty[flr] + " tensundred ")

        curr_hun = curr_hun % 100

        if (curr_hun > 0 && curr_hun < 20)

            answer += (first_twenty[curr_hun] + " ")

        else if (curr_hun % 10 == 0  &&  curr_hun != 0){

            flr = Math.floor(curr_hun / 10);

            answer += (tens[flr - 1] + " ")

        }

        else if (curr_hun > 19  &&  curr_hun < 100){

            flr = Math.floor(curr_hun / 10);

            answer += (tens[flr - 1] + " " +

                       first_twenty[curr_hun % 10] + " ")

        }

        if (t < 4)

            answer += (multiplier[t] + " ")

        i = i % limit

        limit = Math.floor(limit / 1000)

    }

    console.log(answer)

}

let n = 36

numberToWords(n)

n = 123456789

numberToWords(n)

n = 10101010110001

numberToWords(n)

n = 999999999

numberToWords(n)

Output

Thirty Six 
One Hundred Twenty Three Million Four Hundred Fifty Six Thousand Seven Hundred Eighty Nine 
Ten Trillion One Hundred One Billion Ten Million One Hundred Ten Thousand One 
Nine Hundred Ninety Nine Million Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine 

Time Complexity: O(Log10(N))
Auxiliary Space: O(1)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

class Main

{

    private static final String EMPTY = «»;

    private static final String[] X =

    {

        EMPTY, «One «, «Two «, «Three «, «Four «, «Five «, «Six «,

        «Seven «, «Eight «, «Nine «, «Ten «, «Eleven «,«Twelve «,

        «Thirteen «, «Fourteen «, «Fifteen «, «Sixteen «,

        «Seventeen «, «Eighteen «, «Nineteen «

    };

    private static final String[] Y =

    {

        EMPTY, EMPTY, «Twenty «, «Thirty «, «Forty «, «Fifty «,

        «Sixty «, «Seventy «, «Eighty «, «Ninety «

    };

    // Function to convert a single-digit or two-digit number Longo words

    private static String convertToDigit(long n, String suffix)

    {

        // if `n` is zero

        if (n == 0) {

            return EMPTY;

        }

        // split `n` if it is more than 19

        if (n > 19) {

            return Y[(int) (n / 10)] + X[(int) (n % 10)] + suffix;

        }

        else {

            return X[(int) n] + suffix;

        }

    }

    // Function to convert a given number (max 9-digits) Longo words

    public static String convert(long n)

    {

        // for storing the word representation of the given number

        StringBuilder res = new StringBuilder();

        // add digits at ten million and hundred million place

        res.append(convertToDigit((n / 1000000000) % 100, «Billion, «));

        // add digits at ten million and hundred million place

        res.append(convertToDigit((n / 10000000) % 100, «Crore, «));

        // add digits at hundred thousand and one million place

        res.append(convertToDigit(((n / 100000) % 100), «Lakh, «));

        // add digits at thousand and tens thousand place

        res.append(convertToDigit(((n / 1000) % 100), «Thousand, «));

        // add digit at hundred place

        res.append(convertToDigit(((n / 100) % 10), «Hundred «));

        if ((n > 100) && (n % 100 != 0)) {

            res.append(«and «);

        }

        // add digits at ones and tens place

        res.append(convertToDigit((n % 100), «»));

        return res.toString().trim()

                .replace(«, and», » and»)

                .replaceAll(«^(.*),$», «$1»);        // remove trailing comma

    }

    // Java program to convert numbers to words

    public static void main(String[] args)

    {

        System.out.println(convert(99L));

        System.out.println(convert(1000L));

        System.out.println(convert(14632L));

        System.out.println(convert(997751076L));

        System.out.println(convert(2147483647L));

    }

}

Here is a sample I played with. Hope it’s useful.

I’d consider decomposing this into reusable functions.

package com.bluenoteandroid.experimental.ints;

import static com.google.common.base.Optional.*;
import static com.google.common.base.Preconditions.*;
import static java.lang.Math.*;

import java.util.Arrays;
import java.util.LinkedList;

import com.google.common.annotations.Beta;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;

public final class Ints {

    public static final int BASE_10 = 10;

    public static final String MINUS = "minus"; 

    public static final ImmutableMap<Integer, String> NUMBERS = ImmutableMap.<Integer, String>builder()
            .put(0,"zero")
            .put(1,"one")
            .put(2,"two")
            .put(3,"three")
            .put(4,"four")
            .put(5,"five")
            .put(6,"six")
            .put(7,"seven")
            .put(8,"eight")
            .put(9,"nine")
            .put(10,"ten")
            .put(11,"eleven")
            .put(12,"twelve")
            .put(13,"thirteen")
            .put(14,"fourteen")
            .put(15,"fifteen")
            .put(16,"sixteen")
            .put(17,"seventeen")
            .put(18,"eighteen")
            .put(19,"nineteen")
            .put(20,"twenty")
            .put(30,"thirty")
            .put(40,"forty")
            .put(50,"fifty")
            .put(60,"sixty")
            .put(70,"seventy")
            .put(80,"eighty")
            .put(90,"ninety")
            .put(100,"hundred")
            .put(1000,"thousand")
            .put(1000000,"million")
            .put(1000000000,"billion")
            .build();

    private Ints() { /* disabled */ }

    public static boolean allZeros(int[] range) {
        for (int n : range) {
            if (n != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * Counts digits in an integer
     * @param number
     * @return digits count in the number
     */
    public static int digitCount(final int number) {
        return (int) ((number == 0) ? 1 : log10(abs(number)) + 1);
    }

    /**
     * Sums digits in an integer
     * @param number number
     * @return sum of the n's digits
     */
    public static int digitSum(final int number) {
        int _n = abs(number);
        int sum = 0;
        do {
            sum += _n % BASE_10;
        } while ((_n /= BASE_10) > 0);
        return sum;
    }

    /**
     * Gets digit index in an integer, counting from right 
     * @param number number
     * @param index (from right)
     * @return index-th digit from n
     */
    public static int digitFromRight(final int number, final int index) {
        checkElementIndex(index, digitCount(number));
        return (int) ((abs(number) / pow(BASE_10, index)) % BASE_10);
    }

    /**
     * Gets digit of index in an integer, counting from left 
     * @param number
     * @param index (from left)
     * @return index-th digit from n
     */
    public static int digitFromLeft(final int number, final int index) {
        checkElementIndex(index, digitCount(number));
        return digitFromRight(number, digitCount(number) - index - 1);
    }

    /**
     * Converts a number to the array of it's digits
     * @param number number
     * @return array of digits
     */
    public static int[] digits(final int number) {
        return digits(number, digitCount(number));
    }

    /**
     * Converts a number to a reversed array of it's digits
     * @param number number
     * @return reversed array of digits
     */
    public static int[] digitsReversed(final int number) {
        return digitsReversed(number, digitCount(number));
    }

    private static int[] digits(final int number, final int digitCount) {
        final int[] digits = new int[digitCount];

        int _n = abs(number);
        int i = digitCount - 1;
        do {
            digits[i--] = _n % BASE_10;
        } while ((_n /= BASE_10) > 0);
        return digits;
    }

    /**
     * Converts a number to a reversed array of it's digits
     * @param number number
     * @param digitCount digit count
     * @return reversed array of digits
     */
    private static int[] digitsReversed(final int number, final int digitCount) {
        final int[] reversedDigits = new int[digitCount];

        int _n = abs(number);
        int i = 0;
        do {
            reversedDigits[i++] = _n % BASE_10;
        } while ((_n /= BASE_10) > 0);
        return reversedDigits;
    }

    public static int fromDigits(final int[] digits) {
        int n = 0;
        int i = 0;
        do {        
            n += digits[i++];
            if (i >= digits.length) {
                break;
            }
            n *= BASE_10;
        } while (true);
        return n;
    }

    public static int fromDigitsReversed(final int[] reversedDigits) {
        int n = 0;
        int i = reversedDigits.length;
        do {        
            n += reversedDigits[--i];
            if (i <= 0) {
                break;
            }
            n *= BASE_10;
        } while (true);
        return n;
    }

    @Beta
    public static String numberInWords(final int number) {
        Optional<String> name = fromNullable(NUMBERS.get(number));
        if (name.isPresent()) {
            return name.get();
        } else {
            return numberToName(number);
        } 
    }

    private static String numberToName(int number) {        
        final LinkedList<String> words = Lists.newLinkedList();
        final int[] digits = digitsReversed(number);        
        for (int factor = 0; factor < digits.length; factor += 3) {
            final int[] range = Arrays.copyOfRange(digits, factor, factor + 3);
            if (allZeros(range)) {
                continue;
            }

            switch (factor) {
            case 0: /* nothing */
                break;
            case 3: /* thousand */
                words.addFirst(NUMBERS.get((int) pow(BASE_10, 3)));
                break;
            case 6: /* million */
                words.addFirst(NUMBERS.get((int) pow(BASE_10, 6)));
                break;
            case 9: /* billion */
                words.addFirst(NUMBERS.get((int) pow(BASE_10, 9)));
                break;
            default:
                throw new IllegalStateException("Unknown factor: " + factor);
            }

            String part = tripletToWords(range);
            words.addFirst(part);
        }

        if (number < 0) { // negative
            words.addFirst(MINUS);
        }

        return Joiner.on(' ').join(words);
    }

    private static String tripletToWords(final int[] reversedDigits) {
        checkArgument(reversedDigits.length == 3, "This is not a triplet of digits, size: " + reversedDigits.length);

        final int number = fromDigitsReversed(reversedDigits);

        final int[] range = Arrays.copyOfRange(reversedDigits, 0, 2);
        final String dubletWords = dubletToWords(range);

        if (number >= 100) {
            final int thirdDigit = reversedDigits[2];
            final int factor = BASE_10 * BASE_10;
            final String dublet = allZeros(range) ? null : dubletWords;
            return Joiner.on(' ').skipNulls().join(
                    NUMBERS.get(thirdDigit),
                    NUMBERS.get(factor),
                    dublet);
        } else {
            return dubletWords;
        }
    }

    private static String dubletToWords(final int[] reversedDigits) {
        checkArgument(reversedDigits.length == 2, "This is not a dublet of digits, size: " + reversedDigits.length);

        final int number = fromDigitsReversed(reversedDigits);

        Optional<String> name = fromNullable(NUMBERS.get(number));
        if (name.isPresent()) {
            return name.get();
        } else {
            final int firstDigit = reversedDigits[0];
            final int secondDigit = reversedDigits[1];
            final int tens = BASE_10 * secondDigit;
            return Joiner.on('-').join(
                    NUMBERS.get(tens),
                    NUMBERS.get(firstDigit));
        }
    }
}

With unit tests:

package com.bluenoteandroid.experimental.ints;

import static com.bluenoteandroid.experimental.ints.Ints.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.experimental.categories.Categories;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.Suite.SuiteClasses;

import com.bluenoteandroid.experimental.ints.IntsTests.*;

@RunWith(Categories.class)
@SuiteClasses({ 
    CountTest.class, 
    SumTest.class, 
    GetDigitRightTest.class, 
    GetDigitRightPeconditionsTest.class,
    GetDigitLeftTest.class, 
    GetDigitLeftPeconditionsTest.class,
    DigitArrayTest.class,
    FromDigitArrayTest.class,
    ReverseDigitArrayTest.class,
    FromReverseDigitArrayTest.class,
    NumberToWordTest.class
})
public class IntsTests {

    @RunWith(value = Parameterized.class)   
    public static class CountTest {

        private final int input;
        private final int expected;

        public CountTest(final int input, final int expected) {
            this.input = input;
            this.expected = expected;
        }

        @Parameters
        public static Collection<Integer[]> data() {
            return Arrays.asList(new Integer[][] {
                { 0, 1 }, /* input, expected */
                { -1, 1 },
                { 900003245, 9 },
            });
        }

        @Test
        public void shouldCountDigits() {
            assertThat(digitCount(input), is(expected));
        }
    }

    @RunWith(value = Parameterized.class)
    public static class SumTest {

        private final int input;
        private final int expected;

        public SumTest(final int input, final int expected) {
            this.input = input;
            this.expected = expected;
        }

        @Parameters
        public static Collection<Integer[]> data() {
            return Arrays.asList(new Integer[][] {
                { 0, 0 }, /* input, expected */
                { -1, 1 },
                { 1001, 2 },
                { 1234, 1+2+3+4 }
            });
        }

        @Test
        public void shouldSumDigits() {
            assertThat(digitSum(input), is(expected));
        }
    }

    @RunWith(value = Parameterized.class)
    public static class GetDigitRightTest {

        private final int input;
        private final int index;
        private final int expected;

        public GetDigitRightTest(final int input, final int index, final int expected) {
            this.input = input;
            this.index = index;
            this.expected = expected;
        }

        @Parameters
        public static Collection<Integer[]> data() {
            return Arrays.asList(new Integer[][] {
                { 0, 0, 0 }, /* input, expected */
                { -1004, 0, 4 },
                { 1234, 1, 3 },
                { -1234, 2, 2 },
                { 1234, 3, 1 },
            });
        }

        @Test
        public void shouldGetDigits() {
            assertThat(digitFromRight(input, index), is(expected));
        }
    }

    public static class GetDigitRightPeconditionsTest {

        @Test(expected=IndexOutOfBoundsException.class)
        public void shouldNotAllowNegativeIndex() {
            digitFromRight(1234, -1);
        }

        @Test(expected=IndexOutOfBoundsException.class)
        public void shouldNotAllowToBigIndex() {
            digitFromRight(1234, 4);
        }
    }

    @RunWith(value = Parameterized.class)
    public static class GetDigitLeftTest {

        private final int input;
        private final int index;
        private final int expected;

        public GetDigitLeftTest(final int input, final int index, final int expected) {
            this.input = input;
            this.index = index;
            this.expected = expected;
        }

        @Parameters
        public static Collection<Integer[]> data() {
            return Arrays.asList(new Integer[][] {
                { 0, 0, 0 }, /* input, expected */
                { -1004, 0, 1 },
                { 1234, 1, 2 },
                { -1234, 2, 3 },
                { 1234, 3, 4 },
            });
        }

        @Test
        public void shouldGetDigits() {
            assertThat(digitFromLeft(input, index), is(expected));
        }
    }

    public static class GetDigitLeftPeconditionsTest {

        @Test(expected=IndexOutOfBoundsException.class)
        public void shouldNotAllowNegativeIndex() {
            digitFromLeft(1234, -1);
        }

        @Test(expected=IndexOutOfBoundsException.class)
        public void shouldNotAllowToBigIndex() {
            digitFromLeft(1234, 4);
        }
    }

    public static class DigitArrayTest {

        @Test
        public void shouldGetAllDigits() {
            final int[] result = digits(-1234);
            final int[] expected = new int[] {1,2,3,4};
            assertThat(result, is(expected));
        }
    }

    public static class FromDigitArrayTest {

        @Test
        public void shouldConvertDigits() {
            final int result = fromDigits(new int[] {1,2,3,4});
            final int expected = 1234;
            assertThat(result, is(expected));
        }
    }

    public static class ReverseDigitArrayTest {

        @Test
        public void shouldGetAllDigits() {
            final int[] result = digitsReversed(-1234);
            final int[] expected = new int[] {4,3,2,1};
            assertThat(result, is(expected));
        }
    }

    public static class FromReverseDigitArrayTest {

        @Test
        public void shouldConvertDigits() {
            final int result = fromDigitsReversed(new int[] {4,3,2,1});
            final int expected = 1234;
            assertThat(result, is(expected));
        }
    }

    @RunWith(value = Parameterized.class)
    public static class NumberToWordTest {

        private final int input;
        private final String expected;

        public NumberToWordTest(final int input, final String expected) {
            this.input = input;
            this.expected = expected;
        }

        @Parameters
        public static Collection<Object[]> data() {
            return Arrays.asList(new Object[][] {
                { 0, "zero" },
                { 1, "one" },
                { 10, "ten" },
                { 15, "fifteen" },
                { 60, "sixty" },
                { 67, "sixty-seven" },
                { 72, "seventy-two" },
                { 101, "one hundred one" },
                { 205, "two hundred five" },
                { 4589, "four thousand five hundred eighty-nine" },
                { 3333, "three thousand three hundred thirty-three" },
                { 67500, "sixty-seven thousand five hundred" },
                { 100000, "one hundred thousand" },
                { 100567, "one hundred thousand five hundred sixty-seven" },
                { 172346, "one hundred seventy-two thousand three hundred forty-six" },
                { 600700, "six hundred thousand seven hundred" },
                { 678900, "six hundred seventy-eight thousand nine hundred" },
                { 890000, "eight hundred ninety thousand" },
                { 999999, "nine hundred ninety-nine thousand nine hundred ninety-nine" },
                { 999999999, "nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine" },
                { 1999999999, "one billion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine" },
                { -21239, "minus twenty-one thousand two hundred thirty-nine"},
            });
        }

        @Test
        public void test() {
            assertEquals(expected, numberInWords(input));
        }

    }
}

Like this post? Please share to your friends:
  • Int to word java
  • Inspiration meaning of the word
  • Int to word codesys
  • Insights from the word
  • Int excel что это