Convert Digit Number To Words In Java Program
Converting a digit number into its word representation is a common programming challenge. This process involves breaking down the number and mapping each part to its corresponding word. In this article, you will learn how to convert a given integer into its word equivalent using Java.
Problem Statement
The goal is to write a Java program that takes an integer as input and outputs its word representation. For example, if the input is 123, the output should be One Hundred Twenty Three. The program should handle numbers up to a reasonable limit, typically billions or trillions.
Example
If the input number is 789, the expected output is:
Seven Hundred Eighty Nine
Background & Knowledge Prerequisites
To understand this article, you should have a basic understanding of:
- Java fundamentals: Variables, data types, control flow (if-else, loops).
- Arrays: Storing and accessing elements.
- String manipulation: Concatenation and building strings.
- Modular arithmetic: Using the modulo operator (
%) and division (/) to extract digits.
Use Cases or Case Studies
Converting numbers to words has several practical applications:
- Financial applications: Generating checks, invoices, or receipts where amounts need to be written out in words to prevent fraud or ensure clarity.
- Reporting systems: Presenting numerical data in a more human-readable format.
- Accessibility tools: Assisting visually impaired users by reading out numbers.
- Educational software: Helping children learn number names.
- Automated voice systems: Providing spoken representations of numbers.
Solution Approaches
Converting numbers to words typically involves breaking the number into groups of three digits (hundreds, tens, ones) and then processing these groups.
Approach 1: Using Arrays for Word Mapping
This approach uses arrays to store the word representations for single digits, tens, and powers of ten (hundred, thousand, million).
One-line summary: Map number segments to words using pre-defined arrays and process the number in chunks of three digits.
// Convert Digit Number to Words
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
private static final String[] units = {
"", "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[] scales = {
"", "Thousand", "Million", "Billion", "Trillion"
};
public static String convertToWords(long number) {
if (number == 0) {
return "Zero";
}
String words = "";
int scaleIndex = 0;
while (number > 0) {
if (number % 1000 != 0) {
words = convertLessThanOneThousand((int) (number % 1000)) + " " + scales[scaleIndex] + " " + words;
}
number /= 1000;
scaleIndex++;
}
return words.trim();
}
private static String convertLessThanOneThousand(int number) {
String current;
if (number % 100 < 20) {
current = units[number % 100];
number /= 100;
} else {
current = units[number % 10];
number /= 10;
current = tens[number % 10] + " " + current;
number /= 10;
}
if (number > 0) {
current = units[number] + " Hundred " + current;
}
return current.trim();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
long number = scanner.nextLong();
scanner.close();
System.out.println("Word representation: " + convertToWords(number));
}
}
Sample output:
Enter a number: 12345
Word representation: Twelve Thousand Three Hundred Forty Five
Stepwise explanation:
- Define word arrays: Three arrays (
units,tens,scales) are initialized to store the word representations for numbers 0-19, tens (20-90), and magnitude scales (thousand, million, etc.). convertToWords(long number)method:
- Handles the base case where the input number is
0. - Initializes an empty
wordsstring andscaleIndexto track the magnitude (thousands, millions). - Uses a
whileloop to process the number in chunks of three digits (e.g., 123, 456, 789 for 789,456,123). -
number % 1000extracts the last three digits. -
convertLessThanOneThousandis called to convert these three digits into words. - The result is prepended to the
wordsstring along with the appropriate scale (e.g., "Thousand"). -
number /= 1000shifts the number to the right by three digits. -
scaleIndexis incremented. - Finally,
trim()removes any leading/trailing spaces.
convertLessThanOneThousand(int number)method:
- This helper method converts a number less than 1000 into words.
- It first checks if the last two digits (
number % 100) are less than 20. If so, it directly uses theunitsarray. - Otherwise, it processes the ones digit and then the tens digit using the
tensandunitsarrays. - If the number is greater than 0 after processing tens and units (meaning it has a hundreds digit), it prepends the hundreds digit word followed by "Hundred".
-
trim()removes extra spaces.
mainmethod:
- Prompts the user to enter a number.