Convert '165.0' to int

Chris Angelico rosuav at gmail.com
Sat Jul 23 03:42:31 EDT 2011


On Sat, Jul 23, 2011 at 4:53 PM, Frank Millman <frank 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.

If you know that there will always be a trailing point, you can trim
off any trailing 0s, then trim off a trailing '.', and then cast to
int:

int(s.rstrip('0').rstrip('.'))

It'll remove only zeroes and then only periods, as opposed to
s.rstrip('.0') which would give a wrong result for (say) '40.000', so
this should be safe. If there's any non-zero digits after the decimal,
they and the decimal will be kept, which will cause the int() cast to
throw an exception.

ChrisA



More information about the Python-list mailing list