0

How do I change an input float (for example 50300.45) into words in the form of a voucher (fifty thousand three hundred and 45/100 dollars) in python?

Snow
  • 1
  • 2
  • This doesn't answer your question, but I think it might be worthwhile you reading it: https://stackoverflow.com/questions/3730019 – beresfordt Jul 16 '15 at 21:43

1 Answers1

0

To spell out money represented as a decimal string with two digits after the point: spell out the integer part, spell out the fraction:

#!/usr/bin/env python
import inflect # $ pip install inflect

def int2words(n, p=inflect.engine()):
    return ' '.join(p.number_to_words(n, wantlist=True, andword=' '))

def dollars2words(f):
    d, dot, cents = f.partition('.')
    return "{dollars}{cents} dollars".format(
        dollars=int2words(int(d)),
        cents=" and {}/100".format(cents) if cents and int(cents) else '')

for dollars in ['50300.45', '100', '00.00']:
    print(dollars2words(dollars))

Output

fifty thousand three hundred and 45/100 dollars
one hundred dollars
zero dollars

Here's inflect module helps to convert integer to English words. See How do I tell Python to convert integers into words

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670