# Converting Numbers to Words

April 20, 2011 | Arrays in Java

Sometimes it is very much required in coding to convert numbers to words and print them as can be seen in Railway reservation tickets. Explained in "Converting Numbers to Words" with Java syntax.

Following program illustrates "Converting Numbers to Words".

``````import java.util.*;
public class YourNumberMyWord
{
public void pw(int n,String ch)
{
String  one[]={" "," one"," two"," three"," four"," five"," six"," seven"," eight"," Nine"," ten"," eleven"," twelve"," thirteen"," fourteen","fifteen"," sixteen"," seventeen"," eighteen"," nineteen"};

String ten[]={" "," "," twenty"," thirty"," forty"," fifty"," sixty","seventy"," eighty"," ninety"};

if(n &gt; 19) { System.out.print(ten[n/10]+" "+one[n%10]);} else { System.out.print(one[n]);}
if(n &gt; 0)System.out.print(ch);
}
public static void main(String[] args)
{
int n=0;
Scanner scanf = new Scanner(System.in);
System.out.println("Enter an integer number: ");
n = scanf.nextInt();

if(n &lt; = 0)
System.out.println("Enter numbers greater than 0");
}
else
{
YourNumberMyWord a = new YourNumberMyWord();
a.pw((n/1000000000)," Hundred");
a.pw((n/10000000)%100," crore");
a.pw(((n/100000)%100)," lakh");
a.pw(((n/1000)%100)," thousand");
a.pw(((n/100)%10)," hundred");
a.pw((n%100)," ");
}
}
}``````

The integer number is taken from keyboard, converted and printed in words. The number can be taken from a file or database or GUI also. Here, java.util.Scanner class is used to take keyboard input. Other styles of keyboard input are using the classes DataInputStream and BufferedReader.

Code is self-explanatory, involves small logic of separating each digit in the integer number, converting each digit to an array of words, exchanging the word and printing each word.

Precaution: Write as if(n<=0)

All ARRAY Operations at a Glance

Constructor related Topics