Given a string $29,656.9
, using python 2.7, what is the best way to convert it to $29,656.90
That is to say, what is the simplest way ensure that a "price" string always has 2 digits after the decimal place while leaving the $
and any ,
's intact?
My first thought was to convert the str to a float and use the :.2f
format helper, but that doesnt work easily due to the $
and ,
in the string
price = '$29,656.9'
print('{0:.2f}'.format(float(price)))
Of course, this gives:
Traceback (most recent call last):
File "python", line 2, in
ValueError: could not convert string to float: '$29,656.9'
Note: I do not control the input. It is not possible for me to get the raw float value and format it properly to begin with