tags:

views:

50

answers:

1

Hi!

I have three floats that I want to output as a 2 decimal places string.

amount1 = 0.1
amount2 = 0.0
amount3 = 1.87

I want to output all of them as a string that looks like 0.10, 0.00, and 1.87 respectively.

How do I do that efficiently?

+5  A: 

An alternative to directly formatting them is the locale stdlib module

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'en_US.utf8'
>>> locale.currency(123.2342343234234234)
'$123.23'
>>> locale.currency(123.2342343234234234, '')  # the second argument controls the symbol
'123.23'

This is nice because you can just set the locale to the users default as I do and then print in their conventions.

aaronasterling