Thursday, March 19, 2009

How to convert a number into words using Java?

The following example shows how recusion can be used to convert any number from 0 to 99 into words. eg. NumberToWords.numberToWords(34) returns “Thirty Four”.

public class NumberToWords {

private static final String[] ONES = {
"Zero", "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine" };
private static final String[] TEENS = {
"Ten", "Eleven", "Twelve", "Thirteen", null, "Fifteen",
null, null, "Eighteen", null };
private static final String[] TENS = {
null, null, "Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety" };

public static String numberToWords(int number) {
if (number<10)>
return ONES[number];
} else if (number<20)>
int n = number - 10;
String words = TEENS[n];
return words==null ? ONES[n]+"teen" : TEENS[n];
} else {
int n = number % 10;
return TENS[number/10] +
(n==0 ? "" : (" " + numberToWords(n)));
}
}

public static void main(String[] args) {
for (int i=0; i<100;>
System.out.println(i+" "+numberToWords(i));
}
}
}

No comments: