Program to Convert a Given Number to Words | Set 2
Converting numbers to words is a common programming task that finds its applications in various domains, such as finance, where amounts need to be written out in words on checks. In this blog, we will delve into a more advanced approach to converting a given number to words, building upon the concepts covered in Set 1. We'll explore different programming languages and techniques to achieve this task efficiently.
Table of Contents#
- Understanding the Problem
- Common Practices for Number to Word Conversion
- Python Implementation
- Java Implementation
- Best Practices
- Example Usage
- Conclusion
- References
Understanding the Problem#
The goal is to take a numerical input and convert it into its equivalent word representation. For example, the number 123 should be converted to "One hundred twenty - three". We need to handle different digit places, such as units, tens, hundreds, thousands, millions, etc., and use appropriate words for each digit and place value.
Common Practices for Number to Word Conversion#
- Breaking the Number: Break the number into groups of three digits from the right. Each group represents a different place value (thousands, millions, billions, etc.).
- Handling Zero: Special care must be taken when dealing with zeros. For example, 1002 should be "One thousand two", not "One thousand zero hundred two".
- Using Lookup Tables: Create lookup tables for single - digit numbers, teens, and multiples of ten to simplify the conversion process.
Python Implementation#
def number_to_words(num):
if num == 0:
return "Zero"
ones = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
teens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
thousands = ["", "Thousand", "Million", "Billion"]
def convert_chunk(num):
result = ""
if num >= 100:
result += ones[num // 100] + " Hundred "
num %= 100
if num >= 10 and num < 20:
result += teens[num - 10]
else:
if num // 10 > 0:
result += tens[num // 10] + " "
num %= 10
if num > 0:
result += ones[num]
return result.strip()
chunks = []
while num > 0:
chunks.append(num % 1000)
num //= 1000
final_result = ""
for i, chunk in enumerate(chunks):
if chunk > 0:
final_result = convert_chunk(chunk) + " " + thousands[i] + " " + final_result
return final_result.strip()
# Test the function
number = 1234567
print(number_to_words(number))
Java Implementation#
class NumberToWords {
private static final String[] ones = {"", "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"};
private static String convertChunk(int num) {
StringBuilder result = new StringBuilder();
if (num >= 100) {
result.append(ones[num / 100]).append(" Hundred ");
num %= 100;
}
if (num >= 10 && num < 20) {
result.append(teens[num - 10]);
} else {
if (num / 10 > 0) {
result.append(tens[num / 10]).append(" ");
}
num %= 10;
if (num > 0) {
result.append(ones[num]);
}
}
return result.toString().trim();
}
public static String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
StringBuilder finalResult = new StringBuilder();
int i = 0;
while (num > 0) {
if (num % 1000 != 0) {
finalResult.insert(0, convertChunk(num % 1000) + " " + thousands[i] + " ");
}
num /= 1000;
i++;
}
return finalResult.toString().trim();
}
public static void main(String[] args) {
int number = 1234567;
System.out.println(numberToWords(number));
}
}
Best Practices#
- Modular Design: Break the conversion process into smaller functions, such as
convert_chunkin the above examples. This makes the code more readable and easier to maintain. - Error Handling: Although not shown in the examples, it's a good practice to handle invalid inputs, such as negative numbers or non - numerical inputs.
- Code Reusability: The lookup tables can be reused across different parts of the code if needed.
Example Usage#
In a finance application, when printing a check, the amount in numerical form needs to be converted to words. For example, if the amount is 5678.90, the program can first extract the integer part (5678) and convert it to "Five thousand six hundred seventy - eight", and then handle the decimal part separately.
Conclusion#
Converting a number to words is a non - trivial task that requires careful handling of different digit places and edge cases. By following common practices and using modular design, we can create efficient and readable code to achieve this task. The Python and Java implementations provided in this blog serve as a good starting point for your own projects.
References#
- Python official documentation: https://docs.python.org/3/
- Java official documentation: https://docs.oracle.com/javase/8/docs/