将带小数点的浮点数更改为单词

时间:2015-07-16 21:39:00

标签: python-3.x word decimal-point

如何在python中将输入浮点数(例如50300.45)更改为凭证(五万三千和45/100美元)形式的单词?

1 个答案:

答案 0 :(得分:0)

拼出表示为小数字符串的金额,该点后面有两位数:拼出整数部分,拼出分数:

#!/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))

输出

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

此处inflect module helps to convert integer to English words。见How do I tell Python to convert integers into words