JAVA Program to convert Digits\Numbers to Words

Converting Number/Digits to Words

In this page we’ll look at a program using which wwe can convert Numbers entered by the user into words form. Ex. If a user enters ‘94811’ the output will be ‘Ninety  Four Thousand Eight Hundred Fourty One’. The above can be achieved by using two arrays one of which will be storing the words for digit from 1-19 and the other one storing the mutiples of ten that is Twenty, Thirty, Fourty etc.

JAVA Program to convert number/digits to words.

Algorithm

 

  • Take the input from the user.
  • Use two conditional If statements to determine whether the digit is larger then 999 or not. If yes, Divide the number into two parts at the thousands place.
  • Now In the display() function pass the three digit number as a argument where this function will print the number in its words format.

JAVA Program

import java.util.*;
public class Main
{
	public static void main(String[] args) {
	     System.out.println("Enter a Number");
	     Scanner s= new Scanner(System.in);
	     int num=s.nextInt();
	     Main m= new Main();
	     if(num<1000)
	     m.display(num);
	     if(num>999 && num<1000000)
	     {
	         m.display(num/1000);
	         System.out.print("thousand ");
	         m.display(num%1000);
	     }
}
	     void display(int num1)
	     {
	       int one=0,ten,hund,thou;
	       String ones[]={" " , "one", "two ", "three ", "four " , "five ", "six ", "seven ", "eight ", "nine ", "ten" ,
	                  "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen" };
	       String tens[]={" " , " " , "twenty" , "thirty" ,  "fourty" , "fifty" , "sixty" , "seventy" , "eighty" , "ninety"};
	       if(num1<20)
	            System.out.print(ones[num1]);
	       if(num1>19 && num1<100)
	            {
	            one=num1%10;        //extracting the digit at the unit place
	            ten=num1/10;        //extracting the digit at the tens place
	            System.out.print(tens[ten]+" "+ones[one]);
	            }
	      if(num1>99 && num1<1000)
	            {
	            hund=num1/100;      //extracting the digit at the hundreds place
	            ten=num1%100;       //extracting the digit at the tens place
	            if(ten>20)
	            {
	            ten=(num1-(hund*100))/10;   //extracting the digit at the tens place
	            one=num1%10;        //extracting the digit at the units place
	            System.out.print(ones[hund]+" hundred " + tens[ten]+" "+ones[one]);
	            }
	            else
	            System.out.print(ones[hund]+" hundred "+ones[ten]);
	            }
	   
	     }
}
Enter a Number
94811
ninety four thousand eight hundred eleven