Keywords: Java | Number Conversion | Words | Algorithm
Abstract: This article explores a robust method to convert numerical values into their English word representations using Java. It covers the implementation details, code examples, and comparisons with alternative approaches, focusing on the solution from a highly-rated Stack Overflow answer.
Introduction
Converting numbers to their word equivalents is a common requirement in various applications, such as generating invoices, checks, or user-friendly displays. In Java, while there is no built-in library function for this purpose, several custom implementations exist. This article focuses on an efficient method derived from a highly-accepted Stack Overflow answer, which handles numbers up to 999,999,999,999.
Method Overview
The core idea involves breaking down the number into manageable chunks (e.g., billions, millions, thousands) and recursively converting each part using predefined arrays for number names. This approach ensures clarity and performance for most practical use cases.
Code Implementation
Below is a rewritten version of the Java code based on the original solution. It uses static arrays for number names and a recursive helper function to handle numbers less than one thousand.
import java.text.DecimalFormat;
public class NumberToWordsConverter {
private static final String[] tensNames = {
"", " ten", " twenty", " thirty", " forty", " fifty", " sixty", " seventy", " eighty", " ninety"
};
private static final String[] numNames = {
"", " one", " two", " three", " four", " five", " six", " seven", " eight", " nine", " ten",
" eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen"
};
private NumberToWordsConverter() {}
private static String convertLessThanOneThousand(int number) {
if (number == 0) {
return "";
}
String soFar;
if (number % 100 < 20) {
soFar = numNames[number % 100];
number /= 100;
} else {
soFar = numNames[number % 10];
number /= 10;
soFar = tensNames[number % 10] + soFar;
number /= 10;
}
if (number == 0) {
return soFar;
}
return numNames[number] + " hundred" + soFar;
}
public static String convert(long number) {
if (number == 0) {
return "zero";
}
String snumber = Long.toString(number);
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
int billions = Integer.parseInt(snumber.substring(0, 3));
int millions = Integer.parseInt(snumber.substring(3, 6));
int hundredThousands = Integer.parseInt(snumber.substring(6, 9));
int thousands = Integer.parseInt(snumber.substring(9, 12));
StringBuilder result = new StringBuilder();
if (billions > 0) {
result.append(convertLessThanOneThousand(billions)).append(" billion ");
}
if (millions > 0) {
result.append(convertLessThanOneThousand(millions)).append(" million ");
}
if (hundredThousands > 0) {
if (hundredThousands == 1) {
result.append("one thousand ");
} else {
result.append(convertLessThanOneThousand(hundredThousands)).append(" thousand ");
}
}
if (thousands > 0) {
result.append(convertLessThanOneThousand(thousands));
}
return result.toString().trim().replaceAll("\\s+", " ");
}
public static void main(String[] args) {
System.out.println(convert(10183)); // Output: ten thousand one hundred eighty three
System.out.println(convert(90)); // Output: ninety
System.out.println(convert(5888)); // Output: five thousand eight hundred eighty eight
}
}This code first pads the number string to 12 digits to handle up to billions, then splits it into parts for billions, millions, etc., and converts each part using the helper function.
Detailed Explanation
The convertLessThanOneThousand method processes numbers from 0 to 999 by checking the remainder when divided by 100. If the remainder is less than 20, it directly uses the numNames array; otherwise, it handles tens and units separately. The main convert method uses string manipulation to divide the number into segments, each converted recursively.
Comparison with Other Methods
Alternative approaches include using libraries like ICU4J for multilingual support or custom algorithms for larger numbers and decimals, as seen in other answers. For instance, Answer 3 provides a scalable solution for very large numbers, while Answer 4 offers a simpler recursive method for integers. The current method is optimal for English and moderate number ranges.
Conclusion
This Java implementation provides a reliable way to convert numbers to words, balancing simplicity and efficiency. Developers can extend it for other languages or larger scales by modifying the arrays and logic. For production use, consider error handling and localization needs.