Java program for conversion of number into words
import java.util.*;public class NumToWords {
String string;
// String array for printing one to nine
String st1[] = { "", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", };
// String array for printing hundred, thousand, lakh and crore
String st2[] = { "hundred", "thousand", "lakh", "crore" };
// This array will print ten to nineteen
String st3[] = { "ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen", };
// This will print twenty, thirty etc
String st4[] = { "twenty", "thirty", "fourty", "fifty", "sixty", "seventy",
"eighty", "ninty" };
// Conversion method
public String convert(int number)
{
int n = 1;
int word;
string = "";
while (number != 0) {
switch (n) {
case 1:
word = number % 100;
pass(word);
if (number > 100 && number % 100 != 0) {
show("and ");
}
number /= 100;
break;
case 2:
word = number % 10;
if (word != 0) {
show(" ");
show(st2[0]);
show(" ");
pass(word);
}
number /= 10;
break;
case 3:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[1]);
show(" ");
pass(word);
}
number /= 100;
break;
case 4:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[2]);
show(" ");
pass(word);
}
number /= 100;
break;
case 5:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[3]);
show(" ");
pass(word);
}
number /= 100;
break;
}
n++;
}
return string;
}
// pass method
public void pass(int number) {
int word, q;
if (number < 10) {
show(st1[number]);
}
if (number > 9 && number < 20) {
show(st3[number - 10]);
}
if (number > 19) {
word = number % 10;
if (word == 0) {
q = number / 10;
show(st4[q - 2]);
} else {
q = number / 10;
show(st1[word]);
show(" ");
show(st4[q - 2]);
}
}
}
// show method
public void show(String s) {
String st;
st = string;
string = s;
string += st;
}
// main method
public static void main(String[] args) {
NumToWords w = new NumToWords();
Scanner input = new Scanner(System.in);
System.out.print("Enter Number: ");
int num = input.nextInt();
String inwords = w.convert(num);
System.out.println(inwords);
}
} // class end
Output:
Enter Number: 15847
fifteen thousand eight hundred and fourty seven
Enter Number: 154782
one lakh fifty four thousand seven hundred and eighty two
Enter Number: 6520
six thousand five hundred and twenty
Enter Number: 154
one hundred and fifty four
More Java program