Created
August 29, 2012 01:43
-
-
Save alysbrooks/3505951 to your computer and use it in GitHub Desktop.
Print integers as words. (e.g. from '34' to 'thirty-four.')
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class numberWord { | |
//Limited to numbers under 20,000. | |
//TODO punctuate properly | |
public static String spellOut(int n) { | |
if(n == 0) return "zero"; | |
String output = ""; | |
//This method relies on the fact Java drops the remainder of integer division | |
int thousands = n / 1000; | |
n -= thousands * 1000; | |
int hundreds = n / 100; | |
n -= hundreds * 100; | |
int tens = n / 10; | |
n -= tens * 10 * (n > 20 ? 1 : 0); | |
if(thousands > 0) output += digits(thousands) + " thousand "; | |
if(hundreds > 0) output += digits(hundreds) + " hundred "; | |
if(tens >= 2) { | |
String[] names = {null, null, "twenty", "thirty", "forty", "fifty", | |
"sixty", "seventy", "eighty", "ninety"}; | |
output += names[tens] + " "; | |
} | |
if(n > 0) output += digits(n); | |
return output; | |
} | |
private static String digits(int n) { | |
String[] names = {"zero", "one", "two", "three", "four", | |
"five", "six", "seven", "eight", "nine", "ten", | |
"eleven", "twelve", "thirteen", "fourteen", "fifteen", | |
"sixteen", "seventeen", "eighteen", "nineteen", "twenty"}; | |
return ((n < 20) && (n > 0)) ? names[n] : ""; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment