1

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

Community
  • 1
  • 1
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
  • You'll want to parse the string into a number first, that is, remove the dollar sign (`lstrip`, or just `price[1:]`), then convert it to float. Python does not handle units for you, just plain numbers (but some packages can do this for you). –  Nov 29 '16 at 05:30
  • @Evert, both of those would leave the comma though right? Then I'd still have to remove that? Is there really no better way? – Wesley Smith Nov 29 '16 at 05:32
  • Not much of a better way (e.g., nothing like `strptime` that I know of). As for the comma, see e.g. http://stackoverflow.com/questions/1779288/how-do-i-use-python-to-convert-a-string-to-a-number-if-it-has-commas-in-it-as-th –  Nov 29 '16 at 05:35
  • @Evert could you tell me exactly what `[1:]` is doing? (I assume it just removes the first char? but Im not familiar with that syntax) – Wesley Smith Nov 29 '16 at 05:35
  • @Evert that's a shame, I'd have to then put the `$` and `,` back after Im done. Oh we'll, I guess I'll just use a regex replace then – Wesley Smith Nov 29 '16 at 05:37
  • 1
    @DelightedD0D Yes, it strips the first character. The syntax is called [slicing](https://docs.python.org/2/tutorial/introduction.html#strings). – Selcuk Nov 29 '16 at 05:38
  • 1
    @Selcuk thanks on both counts :) dupe question is just what I needed – Wesley Smith Nov 29 '16 at 05:41

0 Answers0