Java Program to Convert Number to Word

Converting a number into its corresponding word form can be beneficial for better readability and understanding in banking or financial applications. Larger numbers can be difficult to read and comprehend, so translating numbers into their word equivalents can be helpful. 

The purpose of this blog is to provide a solution to the problem of converting numbers to their word representation using Java programming. It will cover different aspects of the solution, including the approach, code, and examples. It will also include sample code and examples to help readers better understand the concept.

Example of Java Program to Convert Number to Word

// Java program to print a given number in words. The
// program handles numbers from 0 to 9999

class GFG {
// A function that prints
// given number in words
static void convert_to_words(char[] num)
{
// Get number of digits
// in given number
int len = num.length;

// Base cases
if (len == 0) {
System.out.println("empty string");
return;
}
if (len > 4) {
System.out.println(
"Length more than 4 is not supported");
return;
}

/* The first string is not used, it is to make
array indexing simple */
String[] single_digits = new String[] {
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"
};

/* The first string is not used, it is to make
array indexing simple */
String[] two_digits = new String[] {
"",  "ten",  "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen"
};

/* The first two string are not used, they are to
* make array indexing simple*/
String[] tens_multiple = new String[] {
"",  "",  "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"
};

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

/* Used for debugging purpose only */
System.out.print(String.valueOf(num) + ": ");
/* For single digit number */
if (len == 1) {
System.out.println(single_digits[num[0] - '0']);
return;
}

/* Iterate while num
is not '\0' */
int x = 0;
while (x < num.length) {

/* Code path for first 2 digits */
if (len >= 3) {
if (num[x] - '0' != 0) {
System.out.print(
single_digits[num[x] - '0'] + " ");
System.out.print(tens_power[len - 3]
+ " ");
// here len can be 3 or 4
}
--len;
}

/* Code path for last 2 digits */
else {
/* Need to explicitly handle
10-19. Sum of the two digits
is used as index of "two_digits"
array of strings */
if (num[x] - '0' == 1) {
int sum
= num[x] - '0' + num[x + 1] - '0';
System.out.println(two_digits[sum]);
return;
}

/* Need to explicitly handle 20 */
else if (num[x] - '0' == 2
&& num[x + 1] - '0' == 0) {
System.out.println("twenty");
return;
}

/* Rest of the two digit
numbers i.e., 21 to 99 */
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;
}
}

// Driver Code
public static void main(String[] args)
{
convert_to_words("5684".toCharArray());
convert_to_words("968".toCharArray());
convert_to_words("63".toCharArray());
convert_to_words("1".toCharArray());
}
}

Explanation of the code for Java Program to Convert Number to Word :
As stated, a Java program transforms a numeric input into its corresponding English word representation.It includes a number ranging from 0 to 9999. The code stores strings of English words that represent single digits, two digit numbers, and multiples of ten in arrays. 

It also handles unique situations, such as multiples of ten up to 90 and numbers between 10 and 19. The program iterates through the input number using a loop, converting the first two or last two digits into words depending on the length of the number. The program outputs the number’s converted word representation.

A complete guide to IIT Bombay Spoken Tutorial, here!

Output:

5684: five thousand six hundred eighty four
968: nine hundred sixty eight
63: sixty three
1: one

Example 2

The output and code that follow support numbers up to 15 digits, or from 0 to trillions. The Number to Word Conversion Java program prints the code using the western numbering scheme.

import java.util.Scanner;
public class Converter {
    private static final String[] ones = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
            "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
    private static final String[] tens = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
    private static final String[] thousands = {"", "thousand", "million", "billion", "trillion"};
 
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number to convert to words: ");
        long n = scanner.nextLong();
 
        if (n == 0) {
            System.out.println("Zero");
        } else {
            String word = "";
            int i = 0;
            while (n > 0) {
                if (n % 1000 != 0) {
                    word = cnv(n % 1000) + thousands[i] + " " + word;
                }
                n /= 1000;
                i++;
            }
            System.out.println(word.trim());
        }
    }
 
    private static String cnv(long n) {
        String word = "";
        if (n % 100 < 20) {
            word = ones[(int) (n % 100)];
            n /= 100;
        } else {
            word = ones[(int) (n % 10)];
            n /= 10;
            word = tens[(int) (n % 10)] + " " + word;
            n /= 10;
        }
        if (n != 0) {
            word = ones[(int) n] + " hundred " + word;
        }
        return word;
    }
}

Explanation of the code:

The given Java code converts a given number to its word form up to trillions. The code defines arrays of words for one-digit numbers, ten-digit numbers, and thousands. The program asks the user to enter a number, and then converts the number to words using a while loop. The code also defines a function to convert each three-digit section of the number to its word form. The function separates each three-digit section of the number and then uses the defined arrays to convert each section to its word form. Finally, the program prints the word form of the number to the console.

Check out our blog on Reverse a Number in Java here!

Output:

And here’s the sample output for the program:

Enter a number to convert to words: 45623
forty fivethousand six hundred twenty three

Applications of Number to Word Conversion

In the fields of finance, accounting, and computer science, the number to word conversion has a wide range of applications. It finds utility in translating monetary sums into words for use on official documents, checks, and invoices. Furthermore, in programming, developers employ it to enhance readability and improve the user experience by displaying numbers as words.

Use Cases of Number to Word Conversion

The banking sector is one of the main use cases for number to word conversion. Banks frequently utilize this conversion to print checks and other official documents. Accounting professionals utilize this conversion to generate written financial reports. Moreover, it finds application in e-commerce websites to verbally display product prices, enabling customers to comprehend them effectively.

Examples of Number to Word Conversion in Real Life

  • Cheque Writing: To prevent fraud, checks are printed with the amount written in words.Converting a number to a word enables you to print the precise amount in words.
  • Financial Reports: To help readers understand the company’s financial situation, financial reports in accounting are written in words.
  • E-commerce: Product prices are frequently stated on e-commerce websites, which helps customers better understand the cost of the item.
  • Education: The concept of numbers and words can be taught to children using number to word conversion.
  • Legal Documents: Many legal documents, including agreements, contracts, and deeds, call for the written expression of amounts. Using number to word conversion enables the accurate expression of the amount in words.

Know How to Print ASCII Value in Java, Here!

In conclusion, there are numerous real-world uses for number to word conversion in a variety of industries, including banking, accounting, e-commerce, education, and legal documents. It is a helpful tool that aids in improving the readability and comprehension of numerical data.

We hope you have found our blog  “Java Program to Convert Number to Word: Unlock the Power of Code” insightful and relevant to your Java-related queries. Keep checking for more updates from Java Programming Blogs. You can also website our Newtum for more information about various programs such Core Python, DJANGO, HTML and more. 

About The Author

Leave a Reply