开发者

Output Formatting Python 3.2

I have a question relating to the output of a program.

 def writeOutput():
    output.write(str(gallons) + '\n')
    output.write(str(usage) + '\n')
    output.write(str(sewer) + '\n')
    output.write(str(tax) + '\n')
    output.write(str(total) + '\n')
    output.write('_______________________' + '\n')

This is my write to file 开发者_Go百科function. Does anybody know where I can look to find out how to write 123.45 as "123 dollars 45 cents" with dollars and cents spelled out like that?

Thanks!


This would work:

>>> amount = 123.45
>>> '{} dollars {:.0f} cents'.format(int(amount), (amount - int(amount)) * 100)
'123 dollars 45 cents'


If you have amount stored as a float(*), you can use the % formatting operator as follows:

"%d dollars %d cents" % (int(amount), int(amount * 100 % 100))

or

dollars = int(amount)
"%d dollars %d cents" % (dollars, int((amount - dollars) * 100))

(*) Which you should never do in a real financial app, since floating point is prone to rounding errors; use the Decimal module instead.


In Python 3 (all 3.x?) for "simple" floats you can write:

'{} dollars {} cents'.format( *str(amount).split('.') )

Output:

'123 dollars 45 cents'

Apparently, str() will screw float numbers like 1.0000000001e-15

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜