Convert '165.0' to int

Frank Millman frank at chagford.com
Sat Jul 23 08:53:22 CEST 2011


On Jul 22, 9:59 pm, Terry Reedy <tjre... at udel.edu> wrote:
> On 7/22/2011 1:55 AM, Frank Millman wrote:
>
> > As the OP, I will clarify what *my* requirement is. This discussion
> > has gone off at various tangents beyond what I was asking for.
>
> Typical. Don't worry about it ;-).
>
> > As suggested above, I am only talking about a string containing int
> > literals followed by '.' followed by zero or more zeros.
> > int(float(x)) does the job,
>
> Not given that specification.
>
>  >>> s='123456789012345678901.0'
>  >>> int(float(s))
> 123456789012345683968
>
> > and I am happy with that.
>
> You should only be if you add 'with fewer than 18 digits' after 'int
> literals' to your spec.
>
> > I was just asking if there were any alternatives.
>
>  >>> int(s.split('.')[0])
> 123456789012345678901
>

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.

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.

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.

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

Do you think this would get any traction if I proposed it? Or would it
fall foul of the moratorium?

Frank



More information about the Python-list mailing list