Pages

Monday, June 29, 2015

Convert Numbers to Words

Convert numbers to words..
ex:
100 = one hundred
101 = one hundred and one


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class NumberToWordsConverter {

   final private static String[] units = {"Zero","One","Two","Three","Four",
  "Five","Six","Seven","Eight","Nine","Ten",
  "Eleven","Twelve","Thirteen","Fourteen","Fifteen",
  "Sixteen","Seventeen","Eighteen","Nineteen"};
   final private static String[] tens = {"","","Twenty","Thirty","Forty","Fifty",
  "Sixty","Seventy","Eighty","Ninety"};
   
   public static void main(String[] args){
      System.out.print(convert(312));
   }

   public static String convert(int i) {
      if( i < 20)
         return units[i];
      if( i < 100) 
         return tens[i/10] + ((i % 10 > 0)? " " + convert(i % 10):"");
      if( i < 1000) 
         return units[i/100] + " Hundred" + ((i % 100 > 0)?" and " + convert(i % 100):"");
      if( i < 1000000) 
         return convert(i / 1000) + " Thousand " + ((i % 1000 > 0)? " " + convert(i % 1000):"") ;

      return convert(i / 1000000) + " Million " + ((i % 1000000 > 0)? " " + convert(i % 1000000):"") ;
   }

}

No comments:

Post a Comment