Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert numbers to words using Python?
Converting numbers to words is a common requirement in applications like check writing, invoice generation, and text-based reports. Python's num2words library provides a simple way to convert numerical values to their word representations. For example, converting 1, 2, 29 to "one", "two", "twenty-nine" respectively.
Installing the num2words Library
Before using the library, install it using pip ?
pip install num2words
Basic Number to Words Conversion
The num2words() function converts integers and floats to their word equivalents ?
from num2words import num2words # Convert simple integers print(num2words(42)) # Convert larger numbers print(num2words(1234567)) # Convert decimal numbers print(num2words(13.5))
forty-two one million, two hundred and thirty-four thousand, five hundred and sixty-seven thirteen point five
Advanced Conversion Options
The num2words() function accepts optional parameters for different conversion formats ?
- to: Specifies output format (cardinal, ordinal, year, currency)
- lang: Sets the language for conversion
- currency: Defines currency type when using currency format
from num2words import num2words # Currency conversion (USD) print(num2words(1234.56, to='currency', currency='USD')) # Different language (French) print(num2words(42, lang='fr')) # Ordinal numbers print(num2words(42, to='ordinal')) # Year format print(num2words(2023, to='year'))
one thousand, two hundred and thirty-four dollars, fifty-six cents quarante-deux forty-second twenty twenty-three
Practical Examples
Here are common use cases for number-to-word conversion ?
from num2words import num2words
# Check amount in words
check_amount = 2500.75
print(f"Amount: {num2words(check_amount, to='currency', currency='USD').title()}")
# Position/ranking
position = 3
print(f"Position: {num2words(position, to='ordinal').title()}")
# Multiple numbers conversion
numbers = [15, 100, 1000, 5000]
for num in numbers:
print(f"{num} ? {num2words(num)}")
Amount: One Thousand, Two Hundred And Fifty Dollars, Seventy-Five Cents Position: Third 15 ? fifteen 100 ? one hundred 1000 ? one thousand 5000 ? five thousand
Conclusion
The num2words library provides an efficient way to convert numbers to words in Python. It supports multiple formats including currency, ordinals, and different languages, making it versatile for various applications like financial documents and internationalized software.
