public class FareToWords {
private static final String[] UNITS = {
"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"
};
private static final String[] TEENS = {
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
};
private static final String[] TENS = {
"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
};
private static final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};
public static String fareToWords(double fare) {
int dollars = (int) fare;
int cents = (int) ((fare - dollars) * 100);
String dollarWords = convertToWords(dollars);
String centWords = convertToWords(cents);
return (dollarWords.isEmpty() ? "" : dollarWords + " Dollars")
+ (centWords.isEmpty() ? "" : " and " + centWords + " Cents");
}
private static String convertToWords(int num) {
if (num == 0) {
return "Zero";
}
String words = "";
int index = 0;
while (num > 0) {
if (num % 1000 != 0) {
words = convertThreeDigits(num % 1000) + THOUSANDS[index] + " " + words;
}
num /= 1000;
index++;
}
return words.trim();
}
private static String convertThreeDigits(int num) {
if (num == 0) {
return "";
}
String words = "";
if (num >= 100) {
words += UNITS[num / 100] + " Hundred ";
num %= 100;
}
if (num >= 10 && num <= 19) {
words += TEENS[num - 10] + " ";
} else if (num >= 20) {
words += TENS[num / 10] + " ";
num %= 10;
}
if (num > 0) {
words += UNITS[num] + " ";
}
return words;
}
public static void main(String[] args) {
double fare = 12345.67;
String words = fareToWords(fare);
System.out.println("Fare in words: " + words);
}
}