decimal numbers

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Feb 15 14:43:33 EST 2014


On Sat, 15 Feb 2014 10:57:20 -0800, Luke Geelen wrote:

> hey, is it possible to remove the .0 if it is a valua without something
> behind the poit (like 5.0 gets 5 but 9.9 stays 9.9

Yes, but not easily. First, check the number's fractional part, and if it 
is zero, convert it to an int:

# Here, your value is x
if x % 1 == 0:
    # Exact whole number.
    x = int(x)


But be warned that really big floats are always ints, even if they have a 
decimal point in them! For example:

x = 1.1e20

has a decimal point, but its value is:

110000000000000000000.0

which is a whole number. So perhaps a better way to do this is to operate 
on the number as a string, not as a numeric value:

s = "%s" % x
if s.endswith(".0"):
    s = s[:-2]


If there is anything you don't understand about this code snippet, please 
feel free to ask.

By the way, I see that you are using GoogleGroups to post. GoogleGroups 
has an extremely obnoxious and annoying habit of throwing in blank lines 
between every line of your reply. Could you please read and follow the 
instructions here:

https://wiki.python.org/moin/GoogleGroupsPython


otherwise you are likely to annoy people and may find we stop answering 
your questions. We are volunteers, and aren't being paid to answer your 
questions. If you make it difficult for us, we may just stop.

Thank you in advance.

Any questions, please don't hesitate to ask.



-- 
Steven



More information about the Python-list mailing list