Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIProgram to convert a given number to words

Program to convert a given number to words

Given an integer N, the task is to convert the given number into words.

Examples :

Input: N = 438237764
Output: Four Hundred Thirty Eight Million Two Hundred Thirty Seven Thousand Seven Hundred Sixty Four

Input: N = 1000
Output: One Thousand

Approach: This approach is valid for converting number into words for up to 20 digits, and is basically based on Brute Force Logic.

The idea is to break down the number into International Number System, i.e., smaller groups of three digits (hundreds, tens, and ones), and convert each group into words.

Consider the below illustration:

Suppose N = 1234567

Now, process this number N in groups of three digits from right to left.

Iteration 1:

  • Current Group: 567
  • Word Representation: Five Hundred Sixty-Seven
  • Multiplier: “”

At this point, the partial word representation is “Five Hundred Sixty-Seven”.

Iteration 2:

  • Current Group: 234
  • Word Representation: Two Hundred Thirty-Four
  • Multiplier: Thousand

The updated word representation becomes “Two Hundred Thirty-Four Thousand Five Hundred Sixty-Seven”.

Iteration 3:

  • Current Group: 1
  • English Representation: One
  • Multiplier: Million

Hence, finally the given number into words becomes “One Million Two Hundred Thirty-Four Thousand Five Hundred Sixty-Seven“.

NOTE: 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 of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
string numberToWords(long long int n)
{
    long long int limit = 1000000000000, curr_hun, t = 0;
   
    // If zero return zero
    if (n == 0)
        return ("Zero");
   
    // Array to store the powers of 10
    string multiplier[] = { "", "Trillion", "Billion",
                            "Million", "Thousand" };
   
    // Array to store numbers till 20
    string first_twenty[] = {
        "",        "One",       "Two",      "Three",
        "Four",    "Five",      "Six",      "Seven",
        "Eight",   "Nine",      "Ten",      "Eleven",
        "Twelve""Thirteen""Fourteen", "Fifteen",
        "Sixteen", "Seventeen", "Eighteen", "Nineteen"
    };
 
    // Array to store multiples of ten
    string tens[]
        = { "",      "Twenty""Thirty", "Forty", "Fifty",
            "Sixty", "Seventy", "Eighty", "Ninety" };
 
    // If number is less than 20, return without any further
    // computation
    if (n < 20)
        return (first_twenty[n]);
 
    // Answer variable to store the conversion
    string answer = "";
    for (long long int i = n; i > 0;
         i %= limit, limit /= 1000) {
 
        // Store the value in multiplier[t], i.e n =
        // 1000000, then r = 1, for multiplier(million), 0
        // for multipliers(trillion and billion)
        curr_hun = i / limit;
 
        // It might be possible that the current multiplier
        // is bigger than your number
        while (curr_hun == 0) {
 
            // Set i as the remainder obtained when n was
            // divided by the limit
            i %= limit;
 
            // Divide the limit by 1000, shifts the
            // multiplier
            limit /= 1000;
 
            // Get the current value in hundreds, as
            // English system works in hundreds
            curr_hun = i / limit;
 
            // Shift the multiplier
            ++t;
        }
 
        // If current hundred is greater than 99, Add the
        // hundreds' place
        if (curr_hun > 99)
            answer += (first_twenty[curr_hun / 100]
                       + " Hundred ");
 
        // Bring the current hundred to tens
        curr_hun = curr_hun % 100;
 
        // If the value in tens belongs to [1,19], add using
        // the first_twenty
 
        if (curr_hun > 0 && curr_hun < 20)
            answer += (first_twenty[curr_hun] + " ");
 
        // If curr_hun is now a multiple of 10, but not 0
        // Add the tens' value using the tens array
        else if (curr_hun % 10 == 0 && curr_hun != 0)
            answer += (tens[curr_hun / 10 - 1] + " ");
 
        // If the value belongs to [21,99], excluding the
        // multiples of 10 Get the ten's place and one's
        // place, and print using the first_twenty array
 
        else if (curr_hun > 20 && curr_hun < 100)
            answer += (tens[curr_hun / 10 - 1] + " "
                       + first_twenty[curr_hun % 10] + " ");
 
        // If Multiplier has not become less than 1000,
        // shift it
        if (t < 4)
            answer += (multiplier[++t] + " ");
    }
    return (answer);
}
 
// Driver code.
int main()
{
    // Input 1
    long long int n = 36;
    cout << numberToWords(n) << '\n';
   
    // Input 2
    n = 123456789;
    cout << numberToWords(n) << '\n';
   
    // Input 3
    n = 10101010110001;
    cout << numberToWords(n) << '\n';
   
    // Input 4
    n = 999999999;
    cout << numberToWords(n) << '\n';
    return 0;
}
// This Code is contributed by Alok Khansali


Java




public class GFG {
    static String numberToWords(long n)
    {
        long limit = 1000000000000L, curr_hun, t = 0;
 
        // If zero return zero
        if (n == 0)
            return ("Zero");
 
        // Array to store the powers of 10
        String multiplier[] = { "", "Trillion", "Billion",
                                "Million", "Thousand" };
 
        // Array to store numbers till 20
        String first_twenty[] = {
            "",        "One",       "Two",      "Three",
            "Four",    "Five",      "Six",      "Seven",
            "Eight",   "Nine",      "Ten",      "Eleven",
            "Twelve""Thirteen""Fourteen", "Fifteen",
            "Sixteen", "Seventeen", "Eighteen", "Nineteen"
        };
 
        // Array to store multiples of ten
        String tens[] = { "",        "Twenty", "Thirty",
                          "Forty",   "Fifty""Sixty",
                          "Seventy", "Eighty", "Ninety" };
 
        // If number is less than 20, return without any
        // further computation
        if (n < 20L)
            return (first_twenty[(int)n]);
        String answer = "";
        for (long i = n; i > 0; i %= limit, limit /= 1000) {
 
            // Store the value in multiplier[t], i.e n =
            // 1000000, then r = 1, for multiplier(million),
            // 0 for multipliers(trillion and billion)
            // multiplier here refers to the current
            // accessible limit
            curr_hun = i / limit;
 
            // It might be possible that the current
            // multiplier is bigger than your number
            while (curr_hun == 0) {
 
                // Set i as the remainder obtained when n
                // was divided by the limit
                i %= limit;
 
                // Divide the limit by 1000, shifts the
                // multiplier
                limit /= 1000;
 
                // Get the current value in hundreds, as
                // English system works in hundreds
                curr_hun = i / limit;
 
                // Shift the multiplier
                ++t;
            }
 
            // If current hundred is greater than 99, Add
            // the hundreds' place
            if (curr_hun > 99)
                answer += (first_twenty[(int)curr_hun / 100]
                           + " Hundred ");
 
            // Bring the current hundred to tens
            curr_hun = curr_hun % 100;
 
            // If the value in tens belongs to [1,19], add
            // using the first_twenty
            if (curr_hun > 0 && curr_hun < 20)
                answer
                    += (first_twenty[(int)curr_hun] + " ");
 
            // If curr_hun is now a multiple of 10, but not
            // 0 Add the tens' value using the tens array
            else if (curr_hun % 10 == 0 && curr_hun != 0)
                answer
                    += (tens[(int)curr_hun / 10 - 1] + " ");
 
            // If the value belongs to [21,99], excluding
            // the multiples of 10 Get the ten's place and
            // one's place, and print using the first_twenty
            // array
            else if (curr_hun > 20 && curr_hun < 100)
                answer
                    += (tens[(int)curr_hun / 10 - 1] + " "
                        + first_twenty[(int)curr_hun % 10]
                        + " ");
 
            // If Multiplier has not become less than 1000,
            // shift it
            if (t < 4)
                answer += (multiplier[(int)++t] + " ");
        }
        return (answer);
    }
 
    // Driver code
    public static void main(String args[])
    {
        // Input 1
        long n = 36L;
        System.out.println(numberToWords(n));
 
        // Input 2
        n = 123456789;
        System.out.println(numberToWords(n));
 
        // Input 3
        n = 10101010110001L;
        System.out.println(numberToWords(n));
 
        // Input 4
        n = 999999999;
        System.out.println(numberToWords(n));
    }
}
// This Code is contributed by Alok Khansali


Python




def numberToWords(n):
    limit, t = 1000000000000, 0
 
    # If zero print zero
    if (n == 0):
        print("zero")
        return
 
    # Array to store the powers of 10
    multiplier = ["", "Trillion", "Billion", "Million", "Thousand"]
 
    # Array to store numbers till 20
    first_twenty = ["", "One", "Two",
                    "Three", "Four", "Five",
                    "Six", "Seven", "Eight",
                    "Nine", "Ten", "Eleven",
                    "Twelve", "Thirteen", "Fourteen",
                    "Fifteen", "Sixteen", "Seventeen",
                    "Eighteen", "Nineteen"]
 
    # Array to store multiples of ten
    tens = ["", "Twenty", "Thirty", "Forty", "Fifty",
            "Sixty", "Seventy", "Eighty", "Ninety"]
 
    # If number is less than 20, print without any
    if (n < 20):
        print(first_twenty[n])
        return
    answer = ""
    i = n
    while(i > 0):
        '''
        Store the value in multiplier[t], i.e n = 1000000,
        then r = 1, for multiplier(million), 0 for multipliers(trillion and billion)
        multiplier here refers to the current accessible limit
        '''
        curr_hun = i // limit
 
        # It might be possible that the current multiplier is bigger than your number
        while (curr_hun == 0):
 
            # Set i as the remainder obtained when n was divided by the limit
            i %= limit
 
            # Divide the limit by 1000, shifts the multiplier
            limit /= 1000
 
            # Get the current value in hundreds, as English system works in hundreds
            curr_hun = i // limit
 
            # Shift the multiplier
            t += 1
 
        # If current hundred is greater than 99, Add the hundreds' place
        if (curr_hun > 99):
            answer += (first_twenty[curr_hun // 100] + " tensundred ")
 
        # Bring the current hundred to tens
        curr_hun = curr_hun % 100
 
        # If the value in tens belongs to [1,19], add using the first_twenty
        if (curr_hun > 0 and curr_hun < 20):
            answer += (first_twenty[curr_hun] + " ")
 
        # If curr_hun is now a multiple of 10, but not 0
        # Add the tens' value using the tens array
        elif (curr_hun % 10 == 0 and curr_hun != 0):
            answer += (tens[(curr_hun//10) - 1] + " ")
 
        # If the value belongs to [21,99], excluding the multiples of 10
        # Get the ten's place and one's place, and print using the first_twenty array
        elif (curr_hun > 19 and curr_hun < 100):
            answer += (tens[(curr_hun//10) - 1] + " " +
                       first_twenty[curr_hun % 10] + " ")
 
        # If Multiplier has not become less than 1000, shift it
        if (t < 4):
            answer += (multiplier[t] + " ")
 
        i = i % limit
        limit = limit // 1000
 
    print(answer)
 
 
# Input 1
n = 36
numberToWords(n)
 
# Input 2
n = 123456789
numberToWords(n)
 
# Input 3
n = 10101010110001
numberToWords(n)
 
# Input 4
n = 999999999
numberToWords(n)
 
# This code is contributed by Alok Khansali


C#




// Include namespace system
using System;
 
public class numtowords {
    public static String numberToWords(long n)
    {
        var limit = 1000000000000L;
        long curr_hun;
        var t = 0;
       
        // If zero return zero
        if (n == 0) {
            return ("Zero");
        }
        // Array to store the powers of 10
        String[] multiplier = { "", "Trillion", "Billion",
                                "Million", "Thousand" };
        // Array to store numbers till 20
        String[] first_twenty = {
            "",        "One",       "Two",      "Three",
            "Four",    "Five",      "Six",      "Seven",
            "Eight",   "Nine",      "Ten",      "Eleven",
            "Twelve""Thirteen""Fourteen", "Fifteen",
            "Sixteen", "Seventeen", "Eighteen", "Nineteen"
        };
       
        // Array to store multiples of ten
        String[] tens = { "",        "Twenty", "Thirty",
                          "Forty",   "Fifty""Sixty",
                          "Seventy", "Eighty", "Ninety" };
       
        // If number is less than 20, return without any
        // further computation
        if (n < 20L) {
            return (first_twenty[(int)n]);
        }
        var answer = "";
        for (long i = n; i > 0; i %= limit, limit /= 1000) {
           
            // Store the value in multiplier[t], i.e n =
            // 1000000, then r = 1, for multiplier(million),
            // 0 for multipliers(trillion and billion)
            // multiplier here refers to the current
            // accessible limit
           
            curr_hun = i / limit;
           
            // It might be possible that the current
            // multiplier is bigger than your number
            while (curr_hun == 0) {
               
                // Set i as the remainder obtained when n
                // was divided by the limit
                i %= limit;
               
                // Divide the limit by 1000, shifts the
                // multiplier
                limit /= 1000;
               
                // Get the current value in hundreds, as
                // English system works in hundreds
               
                curr_hun = i / limit;
               
                // Shift the multiplier
                ++t;
            }
           
            // If current hundred is greater than 99, Add
            // the hundreds' place
            if (curr_hun > 99) {
                answer += (first_twenty[(int)((int)curr_hun
                                              / 100)]
                           + " Hundred ");
            }
           
            // Bring the current hundred to tens
            curr_hun = curr_hun % 100;
           
            // If the value in tens belongs to [1,19], add
            // using the first_twenty
           
            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 Multiplier has not become less than 1000,
            // shift it
            if (t < 4) {
                answer += (multiplier[(int)++t] + " ");
            }
        }
        return (answer);
    }
   
    // Driver code
    public static void Main(String[] args)
    {
        // Input 1
        var n = 36L;
        Console.WriteLine(numtowords.numberToWords(n));
       
        // Input 2
        n = 123456789;
        Console.WriteLine(numtowords.numberToWords(n));
       
        // Input 3
        n = 10101010110001L;
        Console.WriteLine(numtowords.numberToWords(n));
       
        // Input 4
        n = 999999999;
        Console.WriteLine(numtowords.numberToWords(n));
    }
}


Javascript




function numberToWords(n)
{
    let limit = 1000000000000, t = 0
    // If zero console.log zero
    if (n == 0)
    {
        console.log("zero")
        return
    }
    // Array to store the powers of 10
    let multiplier = ["", "Trillion", "Billion", "Million", "Thousand"]
 
    // Array to store numbers till 20
    let first_twenty = ["", "One", "Two",
                    "Three", "Four", "Five",
                    "Six", "Seven", "Eight",
                    "Nine", "Ten", "Eleven",
                    "Twelve", "Thirteen", "Fourteen",
                    "Fifteen", "Sixteen", "Seventeen",
                    "Eighteen", "Nineteen"]
 
    // Array to store multiples of ten
    let tens = ["", "Twenty", "Thirty", "Forty", "Fifty",
            "Sixty", "Seventy", "Eighty", "Ninety"]
 
    // If number is less than 20, console.log without any
    if (n < 20)
    {
        console.log(first_twenty[n])
        return
    }
    let answer = ""
    let i = n
    while(i > 0)
    {
        /*
        Store the value in multiplier[t], i.e n = 1000000,
        then r = 1, for multiplier(million), 0 for multipliers(trillion and billion)
        multiplier here refers to the current accessible limit
        */
        let curr_hun = Math.floor(i / limit)
 
        // It might be possible that the current multiplier is bigger than your number
        while (curr_hun == 0)
        {
            // Set i as the remainder obtained when n was divided by the limit
            i %= limit
 
            // Divide the limit by 1000, shifts the multiplier
            limit /= 1000
 
            // Get the current value in hundreds, as English system works in hundreds
            curr_hun = Math.floor(i / limit)
 
            // Shift the multiplier
            t += 1
        }
 
        let flr = Math.floor(curr_hun / 100);
 
        // If current hundred is greater than 99, Add the hundreds' place
        if (curr_hun > 99)
            answer += (first_twenty[flr] + " tensundred ")
 
        // Bring the current hundred to tens
        curr_hun = curr_hun % 100
 
        // If the value in tens belongs to [1,19], add using the first_twenty
        if (curr_hun > 0 && curr_hun < 20)
            answer += (first_twenty[curr_hun] + " ")
 
        // If curr_hun is now a multiple of 10, but not 0
        // Add the tens' value using the tens array
        else if (curr_hun % 10 == 0  &&  curr_hun != 0){
            flr = Math.floor(curr_hun / 10);
            answer += (tens[flr - 1] + " ")
        }
 
        // If the value belongs to [21,99], excluding the multiples of 10
        // Get the ten's place and one's place, and console.log using the first_twenty array
        else if (curr_hun > 19  &&  curr_hun < 100){
            flr = Math.floor(curr_hun / 10);
            answer += (tens[flr - 1] + " " +
                       first_twenty[curr_hun % 10] + " ")
        }
 
        // If Multiplier has not become less than 1000, shift it
        if (t < 4)
            answer += (multiplier[t] + " ")
             
        i = i % limit
        limit = Math.floor(limit / 1000)
    }
 
    console.log(answer)
}
 
// Input 1
let n = 36
 
numberToWords(n)
n = 123456789
 
// Input 2
numberToWords(n)
n = 10101010110001
 
// Input 3
numberToWords(n)
 
// Input 4
n = 999999999
numberToWords(n)
 
// This code is contributed by phasing17.


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 Nine...

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments