1

In Python 3, when I multiply an integer with a float, using a function or directly, I get a wrong answer.

def mult(a,b):
    c= a*b
    return c
mult(10,3.14)

The answer I obtain is 31.400000000000002.

When I tried typecasting the integer value as float as in direct multiplication

a=float(10) 
b=3.14
c=a*b
c

I still get the same answer.

Meanwhile, mult(7,3.2) provides an answer of 22.400000000000002.

screenshot of second multiplication

How do I fix this?

Edit: I agree that a similar question was asked earlier. But, before asking this question, I didn't find that similar question when searched in Google or in stack overflow. Different people use different search queries to search for the same query. So, in my opinion, this question should not be deleted and should stay.

  • This might help: https://docs.python.org/3/tutorial/floatingpoint.html – Fynn Becker Jan 22 '19 at 16:34
  • Try return format(c, '.2f') # give 2 digits after the point because float cannot be precisely represented in python. – MEdwin Jan 22 '19 at 16:40
  • @MEdwin thanks. It works when a float is involved. But, for integer multiplication like mult(7,3), it provides answer as '21.00' and not as 21. And for string multiplications like mult (2, 'James'), I get an error instead of the expected 'James James ' – Sreejish Lal Jan 22 '19 at 17:00

0 Answers0