Skip to content Skip to sidebar Skip to footer

Python How To Format Currency String

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

Solution 1:

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.

Post a Comment for "Python How To Format Currency String"