Convert '165.0' to int

Billy Mays noway at nohow.com
Sat Jul 23 23:53:51 EDT 2011


On 7/23/2011 2:28 PM, rantingrick wrote:
>
> 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."

I'll probably get flak for this, but damn the torpedoes:

def my_int(num):
     import re
     try:
         m = re.match('^(-?[0-9]+)(.0)?$', num)
         return int(m.group(1))
     except AttributeError:
         #raise your own error, or re raise
         raise


--
Bill



More information about the Python-list mailing list