morha13 morha13 - 3 months ago 19
Python Question

Checking decimal point python

I'm trying to create a script that counts to 3 (step size 0.1) using while, and I'm trying to make it not display .0 for numbers without decimal number (1.0 should be displayed as 1, 2.0 should be 2...)
What I tried to do is convert the float to int and then check if they equal. the problem is that it works only with the first number (0) but it doesn't work when it gets to 1.0 and 2.0..

this is my code:

i = 0
while i < 3.1:
if int(i) == i:
print int(i)
else:
print i
i = i + 0.1


that's the output I get:

0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
2.0
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
3.0


the output I should get:

0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
2
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
3


thank you for your time.

Answer

You can remove trailing zeros with '{0:g}'.format(1.00).

i = 0
while i < 3.1:
    if int(i) == i:
        print int(i)
    else:
        print '{0:g}'.format(i)
    i = i + 0.1

See: https://docs.python.org/3/library/string.html#format-specification-mini-language

Update: Too lazy while copy/pasting. Thanks @aganders3

i = 0
while i < 3.1:
    print '{0:g}'.format(i)
    i = i + 0.1
Comments