Convert '165.0' to int

rantingrick rantingrick at gmail.com
Sat Jul 23 14:28:49 EDT 2011


On Jul 23, 1:53 am, Frank Millman <fr... at chagford.com> wrote:
>--------------------------------------------------
> The problem with that is that it will silently ignore any non-zero
> digits after the point. Of course int(float(x)) does the same, which I
> had overlooked.
>--------------------------------------------------

Wait a minute; first you said all you wanted was to cast "string
floats" to integers NOW your changing the rules.

>--------------------------------------------------
> I do not expect any non-zero digits after the point, but if there are,
> I would want to be warned, as I should probably be treating it as a
> float, not an int.
>--------------------------------------------------
Then the solution is a try:except.

py> def castit(value):
...     try:
...         v = int(value)
...         return v
...     except ValueError:
...         return float(value)
...
py> castit('165')
165
py> castit('165.0')
165.0
py> castit('165.333')
165.333
py> castit('3.3')
3.3

>--------------------------------------------------
> To recap, the original problem is that it would appear that some third-
> party systems, when serialising int's into a string format, add a .0
> to the end of the string. I am trying to get back to the original int
> safely.
>--------------------------------------------------

But you also said you wanted floats too, i am confused??

>--------------------------------------------------
> The ideal solution is the one I sketched out earlier - modify python's
> 'int' function to accept strings such as '165.0'.
>--------------------------------------------------

NO! You create your OWN casting function for special cases.

PythonZEN: "Special cases aren't special enough to break the rules."



More information about the Python-list mailing list