how to improve this simple block of code

Peter Hansen peter at engcorp.com
Thu Jan 12 00:02:42 CET 2006


Ron Griswold wrote:
> How 'bout:
> 
> X = "132.00";
> Y = int(float(X));

This fails on anything that isn't already an integer (in the math sense, 
not the Python type sense), such as 132.15 which was one of the OP's 
actual examples.

Matt's answer is still the only one that passes the tests.  Mel's is 
correct provided the OP's input data is limited in several ways, which 
it may well be.  (For example, the '%g' approach fails if the input has 
too many decimal places, such as 132.0001 or 1234567.  It also can't 
handle non-numbers or empty input, though the OP may not care about any 
of these cases.)

All this goes to show there are a *lot* of ways to write code that 
doesn't work, but apparently only one way to be sure it works.

--
Peter




More information about the Python-list mailing list