0

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.

Patrick Artner
  • 43,256
  • 8
  • 36
  • 57
  • Possible duplicate of [Formatting floats in Python without superfluous zeros](https://stackoverflow.com/questions/2440692/formatting-floats-in-python-without-superfluous-zeros) – Marcus Jan 28 '19 at 12:32

2 Answers2

1

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?)

Patrick Artner
  • 43,256
  • 8
  • 36
  • 57
0

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

print(int(a/b)) 
Bhargav Rao
  • 41,091
  • 27
  • 112
  • 129
Brandon Bailey
  • 723
  • 5
  • 12