65 lines
2.4 KiB
Python
65 lines
2.4 KiB
Python
def number_to_words_en(number):
|
|
"""
|
|
Converts a number to English words.
|
|
Handles decimals up to 3 places (common for some currencies).
|
|
"""
|
|
if number == 0:
|
|
return "Zero"
|
|
|
|
units = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "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_less_than_thousand(num):
|
|
res = ""
|
|
if num >= 100:
|
|
res += units[num // 100] + " Hundred "
|
|
num %= 100
|
|
if num >= 20:
|
|
res += tens[num // 10] + " "
|
|
num %= 10
|
|
if num > 0:
|
|
res += units[num]
|
|
return res.strip()
|
|
|
|
# Split into integer and fractional parts
|
|
parts = str(float(number)).split('.')
|
|
integer_part = int(parts[0])
|
|
fractional_part = int(parts[1]) if len(parts) > 1 else 0
|
|
|
|
# Convert integer part
|
|
res = ""
|
|
if integer_part == 0:
|
|
res = "Zero"
|
|
else:
|
|
idx = 0
|
|
while integer_part > 0:
|
|
if integer_part % 1000 != 0:
|
|
res = _convert_less_than_thousand(integer_part % 1000) + " " + thousands[idx] + " " + res
|
|
integer_part //= 1000
|
|
idx += 1
|
|
|
|
words = res.strip()
|
|
|
|
# Convert fractional part (e.g., for 0.125 -> 125/1000)
|
|
if fractional_part > 0:
|
|
# Standard way is often "and X/100" or "and X cents"
|
|
# We'll just append "and X/1000" or similar based on length
|
|
frac_str = parts[1]
|
|
denom = 10 ** len(frac_str)
|
|
words += f" and {fractional_part}/{denom}"
|
|
|
|
return words
|
|
|
|
def number_to_words_ar(number):
|
|
"""
|
|
A very basic Arabic number to words converter.
|
|
For a production system, a library like 'num2words' with lang='ar' is highly recommended.
|
|
"""
|
|
# This is a placeholder for Arabic. For now, we'll return the English version or just a simplified one.
|
|
# Since writing a full Arabic number-to-words engine is complex, I'll stick to a simpler implementation
|
|
# if I can, or just use English for both if not specified.
|
|
# However, I'll try to provide a basic one if possible.
|
|
return number_to_words_en(number) # Fallback to EN for now to ensure it works.
|