How to convert number to words in java / Java program to convert a number to its word representation

Problem

Write a program in java which reads a number from the console and converts the number to its word form. Example, if the number entered is 23, the program should print twenty three. For input 3435, it should print three thousand four hundred thirty five and so on.

Program

Program to convert the number entered in digits to its word representation is given below.

import java.util.Scanner;
import java.util.Scanner;
 
public class NumberToWordConverter {
 
	public static void main(String[] args) {
		int number = 0;
		Scanner scanner = new Scanner(System.in);
		System.out.println("Please type a number(max upto 9 digits)");
		try {
			// read the number
			number = scanner.nextInt();
			if (number == 0) {
				System.out.print("Number in words: Zero");
			} else {
				System.out.print("Number in words: " + numberToWord(number));
			}
		} catch (Exception e) {
			System.out.println("Please enter a valid number");
		}
		// close the reader
		scanner.close();
	}
 
	private static String numberToWord(int number) {
                // variable to hold string representation of number 
                String words = "";
		String unitsArray[] = { "zero", "one", "two", "three", "four", "five", "six", 
                                "seven", "eight", "nine", "ten", "eleven", "twelve",
                                "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", 
                                "eighteen", "nineteen" };
		String tensArray[] = { "zero", "ten", "twenty", "thirty", "forty", "fifty",
                                 "sixty", "seventy", "eighty", "ninety" };
 
		if (number == 0) {
			return "zero";
		}
		// add minus before conversion if the number is less than 0
		if (number < 0) { 
                        // convert the number to a string
                        String numberStr = "" + number;
                        // remove minus before the number 
                        numberStr = numberStr.substring(1);
                        // add minus before the number and convert the rest of number
                        return "minus " + numberToWord(Integer.parseInt(numberStr));
                } 
                // check if number is divisible by 1 million
                if ((number / 1000000) > 0) {
			words += numberToWord(number / 1000000) + " million ";
			number %= 1000000;
		}
		// check if number is divisible by 1 thousand
		if ((number / 1000) > 0) {
			words += numberToWord(number / 1000) + " thousand ";
			number %= 1000;
		}
		// check if number is divisible by 1 hundred
		if ((number / 100) > 0) {
			words += numberToWord(number / 100) + " hundred ";
			number %= 100;
		}
 
		if (number > 0) {
			// check if number is within teens
			if (number < 20) {
                                 // fetch the appropriate value from unit array
                                 words += unitsArray[number];
                        } else { 
                                // fetch the appropriate value from tens array
                                words += tensArray[number / 10]; 
                                if ((number % 10) > 0) {
				   words += "-" + unitsArray[number % 10];
                            }  
			}
		}
 
		return words;
	}
 
}

Output

Please type a number(max upto 9 digits)
45673
Number in words: forty-five thousand six hundred seventy-three

Please type a number(max upto 9 digits)
-3424
Number in words: minus three thousand four hundred twenty-four

Logic

The program reads a number from the console and passes it on to the method numberToWord. This method declares two arrays : one holds the word representation of numbers from 0 to 19(one, two, three, four etc. ) and other which holds the tens representation of numbers(ten, twenty, thirty etc.).
numberToWord is a recursive method which has multiple if-else conditions which divide the number by 10, 100, 1000, 10000 and so on. This can be increased depending on the maximum limit of the number. Based on the multiple of ten which divides the number, it calculates the quotient and calls itself again with the leftmost digit removed for converting the next digit to a word. Example,

Suppose the number is 3435, the method will check that the number is divisible by 1000. Hence the if condition (number / 1000 > 0) is executed. It will calculate the quotient of division 3435 / 1000 = 3. The if condition which divides the number by 1000 knows that it has divided the number by thousand, it appends the word “thousand” after the quotient and calls the method again with the remaining number 435. The remaining number is calculated by taking modulus of number by the multiple of 10 which divides the number(1000, in this case). Thus modulus is calculated as 3435 % 1000 = 435.

Now, if condition which divides the number by 100 is met and the number is divided by 100 which gives the quotient as 4. Hundred is appended after 4 and the method is called with 35(435 % 100 = 35). Same process is repeated again till the number passed as argument does not meet any of the if conditions and final result is returned.

If the number is negative, the string “minus” is added before the number and “-” symbol is removed by converting the number to a string and then calling substring(1) of String class to remove the minus symbol.

Let’s tweak in

  1. The program reads the number as an integer. Thus, it can handle input values of length 9 only which means till 100s million. If you want to increase the range further, use bigger data types such as long, BigInteger etc.
  2. The program converts the numbers into words based on International numbering system. A little modification is needed to convert it into Indian numbering system.
  3. If minus symbol is not removed when the number is negative, the program will give a java.lang.StackOverflowError since the number will remain negative and it will keep on executing the same if condition which checks whether the number is less than 0 and the method will keep on calling itself in an infinite loop.