I would define DECADES[0]
as "" instead of "zero" so that the if (tens>0)
can be removed. Notice that DECADES[0]
was never used and its value "zero" was a repetition with respect to SUBTWENTY[0]
.
Also there is a repetition in the creation of the "subhundred" part of the number.
In fact you can safely remove this part of code:
if (value < SUBTWENTY.length) {
return SUBTWENTY[value];
}
which is anyway correctly handled by the code following.
Looking carefully you see that there is a problem with the handling of "zero". Try your code with 1000 to see that it doesn't work.
Notice however that the tripleAsText
should return the emptystring when value is 0, because "zero" should be considered as a special case and trapped in the main function (notice that "zero" is never used in the spelling of numbers apart from zero itself).
So your function could be simplified as:
private static final String[] SCALES = {"", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion"};
private static final String[] SUBTWENTY = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
private static final String[] DECADES = {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
/**
* Convert any value from 0 to 999 inclusive, to a string.
* @param value The value to convert.
* @param and whether to use the word 'and' in the output.
* @return a String representation of the value.
*/
private static final String tripleAsText(int value, boolean and) {
int subhun = value % 100;
int hun = value / 100;
StringBuilder sb = new StringBuilder(50);
if (hun > 0) {
sb.append(SUBTWENTY[hun]).append(" hundred ");
if (subhun > 0 && and) {
sb.append("and ");
}
}
if (subhun < SUBTWENTY.length) {
sb.append(SUBTWENTY[subhun]);
} else {
int tens = subhun / 10;
int units = subhun % 10;
sb.append(DECADES[tens]);
if (units>0) {
sb.append(" ");
}
sb.append(SUBTWENTY[units]);
}
return sb.toString();
}