Skip to content

Instantly share code, notes, and snippets.

@KorbenC
Created April 4, 2014 15:09
Show Gist options
  • Select an option

  • Save KorbenC/9976653 to your computer and use it in GitHub Desktop.

Select an option

Save KorbenC/9976653 to your computer and use it in GitHub Desktop.
Print out the text form of numbers from 1 - 1000000(eg 20 is "twenty")
public class ConvertNumToText {
public static String[] digits = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
public static String[] teens = {"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
public static String[] tens = {"Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
public static String[] bigs = {"", "Thousand", "Million"};
public static void main(String[] args) {
for (int i = 1; i < 1000001; i++){
System.out.println(numToString(i));
}
}
public static String numToString(int number){
if (number == 0){
return "Zero";
} else if(number < 0){
return "Negative " + numToString(-1 * number);
}
int count = 0;
String str = "";
while (number > 0){
if (number % 1000 != 0){
str = numToString100(number %1000) + bigs[count] + " " + str;
}
number /= 1000;
count++;
}
return str;
}
public static String numToString100(int number){
String str = "";
if (number >= 100){
str += digits[number / 100 - 1] + " Hundred ";
number %= 100;
}
if (number >= 11 && number <= 19){
return str + teens[number - 11] + " ";
} else if(number == 10 || number >= 20){
str += tens[number / 10 - 1] + " ";
number %= 10;
}
if (number >= 1 && number <= 9){
str += digits[number - 1] + " ";
}
return str;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment