Welcome, guest | Sign In | My Account | Store | Cart

Converts Integers to Words.

Java, 31 lines
 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
28
29
30
31
/**
 * 
 */
package org.mechaevil.util.Conversions;

/**
 * @author st0le
 *
 */
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 String convert(Integer 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):"") ;
	}



}

2 comments

Jero Dungog 10 years, 8 months ago  # | flag

thank you so much for your code sir! it helped me a lot... and i just added some codes to allow a user to in-code and to print out the result, and modified it to billions :)) thanks again

David Ladapo 9 years, 1 month ago  # | flag

A design pattern driven version of this program is now available. Please help expand it to translate numbers to words in other languages. https://sourceforge.net/projects/numberreader/

Created by st0le on Sun, 18 Jul 2010 (MIT)
Java recipes (20)
st0le's recipes (4)

Required Modules

  • (none specified)

Other Information and Tasks