Alli OGrady
Alli OGrady

Reputation: 287

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 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!

Upvotes: 1

Views: 1550

Answers (3)

JSmyth
JSmyth

Reputation: 1504

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

Upvotes: 0

MRAB
MRAB

Reputation: 20644

This would work:

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

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363467

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.

Upvotes: 1

Related Questions