morha13
morha13

Reputation: 1937

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.

Upvotes: 1

Views: 236

Answers (2)

aganders3
aganders3

Reputation: 5945

Due to lack of precision in floating point numbers, they will not have an exact integral representation. Therefore, you want to make sure the difference is smaller than some small epsilon.

epsilon = 1e-10
i = 0
while i < 3.1:
    if abs(round(i) - i) < epsilon:
        print round(i)
    else:
        print i
    i = i + 0.1

Upvotes: 3

adabsurdum
adabsurdum

Reputation: 91

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

Upvotes: 2

Related Questions