Skip to content

Instantly share code, notes, and snippets.

@Maxopoly
Created April 22, 2019 22:24
Show Gist options
  • Save Maxopoly/3c47cb090ee0bfd9e32f50caca706461 to your computer and use it in GitHub Desktop.
Save Maxopoly/3c47cb090ee0bfd9e32f50caca706461 to your computer and use it in GitHub Desktop.
Convert integers into english language
public static String formatNumber(int i) {
boolean bigger = false;
StringBuilder sb = new StringBuilder();
if (i >= 1000) {
int thousands = i / 1000;
i -= (thousands * 1000);
sb.append(formatNumber(thousands));
sb.append(" thousand ");
bigger = true;
}
if (i >= 100) {
int hundreds = i / 100;
i -= (hundreds * 100);
sb.append(formatNumber(hundreds));
sb.append(" hundred ");
bigger = true;
}
if (i != 0) {
if (bigger) {
sb.append("and ");
}
if (i < 10) {
sb.append(getPrimitiveNumber(i));
} else if (i < 20) {
sb.append(getTeenNumber(i));
} else {
int tens = i / 10;
i -= (tens * 10);
sb.append(getTens(tens));
if (i != 0) {
sb.append("-");
sb.append(getPrimitiveNumber(i));
}
}
}
return sb.toString();
}
public static String getTens(int i) {
switch (i) {
case 1:
return "ten";
case 2:
return "twenty";
case 3:
return "thirty";
case 4:
return "forty";
case 5:
return "fifty";
case 6:
return "sixty";
case 7:
return "seventy";
case 8:
return "eighty";
case 9:
return "ninety";
}
throw new IllegalArgumentException();
}
public static String getPrimitiveNumber(int i) {
switch (i) {
case 1:
return "one";
case 2:
return "two";
case 3:
return "three";
case 4:
return "four";
case 5:
return "five";
case 6:
return "six";
case 7:
return "seven";
case 8:
return "eight";
case 9:
return "nine";
}
throw new IllegalArgumentException();
}
public static String getTeenNumber(int i) {
switch (i) {
case 10:
return "ten";
case 11:
return "eleven";
case 12:
return "twelve";
case 13:
return "thirteen";
case 14:
return "fourteen";
case 15:
return "fifteen";
case 16:
return "sixteen";
case 17:
return "seventeen";
case 18:
return "eighteen";
case 19:
return "nineteen";
}
throw new IllegalArgumentException();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment