Python program to print number in words

In this tutorial, we are going to learn how to convert a number to its wording [digit-wise]. For instance, if the number is 12, the wordings will be “one-two”. A similar thing will be done for the rest of the inputs.

Code Implementation

We would be following a number of steps which are mentioned below:

Step 1: Creating a Global list for digit to word mapping

Create a global list containing wordings for each digit from 0 to 9. The list will contain elements mapped to the index as shown in the table below.

Index 0 1 2 3 4 5 6 7 8 9
Wording / Value zero one two three four five six seven eight nine
Global list for digit to word mapping

# Global Array storing word for each digit
arr = ['zero','one','two','three','four','five','six','seven','eight','nine']

Step 2: Taking the input of the number and creating the main function

To take input of the number we will make use of input function and then typecast it to integer and also we will create an empty function that will convert our number to words digit-wise.

# Global Array storing word for each digit
arr = ['zero','one','two','three','four','five','six','seven','eight','nine']

def number_2_word[n]:
    pass

n = int[input[]]
print["Number Entered was : ", n]
print["Converted to word it becomes: ",end=""]
print[number_2_word[n]]

Step 3: Coding the Main Logic Inside the Function

For this code, we will be making use of Recursion. If you have very little or no knowledge about Recursion I would recommend you to check out the tutorial mentioned below:

Read more on Recursion: Recursion in Python

For every recursive call, we will check if my number became 0, if it did we would return an empty string otherwise we will keep adding the wordings for each digit with the help of the modulus function and divide the number by 10 to shrink the number and move to the next digit.

The code implementation is shown below and comments are added for your understanding.

# Global Array storing word for each digit
arr = ['zero','one','two','three','four','five','six','seven','eight','nine']

def number_2_word[n]:

    # If all the digits are encountered return blank string
    if[n==0]:
        return ""
    
    else:
        # compute spelling for the last digit
        small_ans = arr[n%10]

        # keep computing for the previous digits and add the spelling for the last digit
        ans = number_2_word[int[n/10]] + small_ans + " "
    
    # Return the final answer
    return ans

n = int[input[]]
print["Number Entered was : ", n]
print["Converted to word it becomes: ",end=""]
print[number_2_word[n]]

Outputs:

Number Entered was :  123
Converted to word it becomes: one two three

Number Entered was :  46830
Converted to word it becomes: four six eight three zero 

Conclusion

So by end of this tutorial, we saw that the numbers can easily be converted to the wording [digit-wise] in a pretty easy and simple way by the use of Recursion.

Thank you for reading! Happy Learning! 😇

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    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

    #include

    #include

    void convert_to_words[char* num]

    {

        int len = strlen[

            num];

        if [len == 0] {

            fprintf[stderr, "empty string\n"];

            return;

        }

        if [len > 4] {

            fprintf[stderr,

                    "Length more than 4 is not supported\n"];

            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["%s\n", single_digits[*num - '0']];

            return;

        }

        while [*num != '\0'] {

            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["%s\n", two_digits[sum]];

                    return;

                }

                else if [*num == '2' && *[num + 1] == '0'] {

                    printf["twenty\n"];

                    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

    Javascript

    function convert_to_words[num]{

        let l = num.length

        if [l == 0]{

            document.write["empty string","
    "
    ]

            return

        }

        if [l > 4]{

            document.write["Length more than 4 is not supported","
    "
    ]

            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],"
    "
    ]

            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],"
    "
    ]

                    return

                }

                else if [num.charCodeAt[x] - 48 == 2 &&

                      num.charCodeAt[x + 1] - 48 == 0]{

                    document.write["twenty","
    "
    ]

                    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],"
    "
    ]

                }

            }

            x += 1

        }

    }

    convert_to_words["9923"]

    convert_to_words["523"]

    convert_to_words["89"]

    convert_to_words["8"]

    Output

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

    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

    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 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]

    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]


    How do I print numbers in words in Python?

    num2words module in Python, which converts number [like 34] to words [like thirty-four]. Also, this library has support for multiple languages.

    How do I print numbers in words?

    Logic to print number in words: Extract the last digit of a given number by performing modulo division by 10 and store the result in a variable. Now create a switch case to print digit 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Remove the last digit of a number. Repeat steps 3 to 5 until the number becomes 0.

    How do I print a number in a string in Python?

    In Python an integer can be converted into a string using the built-in str[] function. The str[] function takes in any python data type and converts it into a string. But use of the str[] is not the only way to do so. This type of conversion can also be done using the “%s” keyword, the .

    How do I tell Python to convert integers into words?

    Use these two lists to create a dictionary which converts from numbers to words. This is the code I have written for this: numbers = [x for x in range[0, 10]] #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] numWords = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

    Chủ Đề