Convert '165.0' to int

Frank Millman frank at chagford.com
Fri Jul 22 01:55:08 EDT 2011


On Jul 21, 10:00 pm, Terry Reedy <tjre... at udel.edu> wrote:
> On 7/21/2011 10:13 AM, Grant Edwards wrote:
>
> > On 2011-07-21, Web Dreamer<webdrea... at nospam.fr>  wrote:
> >> Leo Jay a ?crit ce jeudi 21 juillet 2011 11:47 dans
>
> >> int(x.split('.')[0])
>
> >> But, the problem is the same as with int(float(x)), the integer number is
> >> still not as close as possible as the original float value.
>
> > Nobody said that "close as possible to the original float value" was
> > the goal.  Perhaps the OP just wants it truncated.
>
> The OP did not specify the domain of possible inputs nor the desired
> output for all possible inputs. Without that, function design is
> guessing. The appropriate response to the original post would have been
> a request for clarification.
>
> If the domain is strings with and int followed by '.0', then chopping
> off two chars is sufficient. This was sort of implied by the original
> post, since it was the only example, and assumed by the respondant.
>
> If the domain is int literals followed by '.' and some number of zeroes,
> then split works. So does int(float(s)). Split also works for non-digits
> following '.' whereas int(float(s)) does not.
>
> If the domain is all float literals, then ??????.
>
> --
> Terry Jan Reedy

As the OP, I will clarify what *my* requirement is. This discussion
has gone off at various tangents beyond what I was asking for.

As suggested above, I am only talking about a string containing int
literals followed by '.' followed by zero or more zeros.

I think that there is a case for arguing that this is a valid
representation of an integer. It would therefore not be unreasonable
for python to accept int('165.0') and return 165. I would expect it to
raise an exception if there were any non-zero digits after the point.

However, the fact is that python does not accept this, and I am not
asking for a change.

int(float(x)) does the job, and I am happy with that. I was just
asking if there were any alternatives.

Frank



More information about the Python-list mailing list