strings (dollar.cents) into floats
Marshall T. Vandegrift
llasram at gmail.com
Thu Aug 30 10:28:33 EDT 2007
luca bertini <luca.bertini at email.it> writes:
> i have strings which look like money values (ie 34.45)
> is there a way to convert them into float variables?
> everytime i try I get this error: "numb = float(my_line) ValueError:
> empty string for float()"
> "
You actually have problems here -- the immediate, and the one which will
get you later :-). First, that error message indicates that you passed
an empty string to `float()`:
>>> float("")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: empty string for float()
Second, if you the values your script is handling are actually monetary
values, you really don't want to represent them with `float`s anyway:
>>> float("34.45")
34.450000000000003
Binary floating point values are necessarily inexact. I'm not 100% sure
what the best-practices are for representing monetary values in Python,
but the `decimal` module is probably a good start.
HTH,
-Marshall
More information about the Python-list
mailing list