Marc Monfort
Marc Monfort

Reputation: 31

Avoid decimal part in python

Is there a way in Python to avoid the decimal part of number result when it is zero?

When a = 12 and b = 2 I want:

print(a/b)

to print:

6   # not 6.0

and if a = 13 and b = 2

6.5 # not 6

in a generic way.

Upvotes: 0

Views: 76

Answers (2)

Brandon Bailey
Brandon Bailey

Reputation: 811

You can use the int()/ round() methods. All one would have to do is

print(int(a/b)) 

Upvotes: 0

Patrick Artner
Patrick Artner

Reputation: 51643

You can use floor division if b divides a without remainder and normal division else:

data = [ (12,2),(13,2)]

for a,b in data:
    print(f"{a} / {b} = ",  a // b if (a//b == a/b) else a / b) 

Output:

12 / 2 = 6
13 / 2 = 6.5

This is a ternary coditional statement (more: Does Python have a ternary conditional operator?) and it evaluates a//b == a/b.

a//b is floordiv and a/b is normal div, they are only ever equal if b divides a without remainder (more: What is the difference between '/' and '//' when used for division?)

Upvotes: 1

Related Questions