-1

In the same function, I have tried to use integer, float, and rounding, but I could not get this result. What did I do wrong?

The goal is:

10*12.3 = 123

3*12.3= 36.9

my code:

def multi(n1, n2):
    x = n1*n2
    return x

I have tried int(n1*n2), but I got 123 and 36. Then I tried float(n1*n2) and I got 123.0 and 36.9. What did I do wrong and how can I fix it?

Filip
  • 819
  • 1
  • 7
  • 23
Alice
  • 3
  • 2
  • You are not doing anything wrong. If you multiply a float by another number (int or float) the result will always be a float. – Selcuk Mar 19 '20 at 08:09

2 Answers2

0

The number is not the representation of the number. For example, all these representations are 123:

123
12.3E1
123.0
123.0000000000000000000

My advice is to do them as floating point and either use output formatting to get them all in a consistent format:

>>> for i in (12.3 * 10, 42., 36.9 / 10):
...     print(f"{i:8.2f}")
...
  123.00
   42.00
    3.69

or string manipulation to remove useless suffixes:

>>> import re
>>> x = 12.3 * 10
>>> print(x)
123.0
>>> print(re.sub(r"\.0*$", "", str(x)))
123
paxdiablo
  • 814,905
  • 225
  • 1,535
  • 1,899
0

You are always multiplying an integer with a float which will always output a float.

If you want the number that your function returns to be a float with 1 decimal point you can use round(num, 1).

def multi(n1, n2):
    x = n1*n2
    return round(x, 1)

print(multi(10, 12.3))  # outputs '123.0'
print(multi(3, 12.3))  # outputs '36.9'

To escape the .0 you could probably use an if statement although I don't see the use of it, since doing calculations with floats have the same output as integers (when they are .0)

def multi(n1, n2):
    x = n1 * n2
    return round(x, 1)

output = []
output.append(multi(10, 12.3))  # outputs '123.0'
output.append(multi(3, 12.3))  # outputs '36.9'

for index, item in enumerate(output):
    if int(item) == float(item):
        output[index] = int(item)

print(output)  # prints [129, 36.9]

This should probably help you but it shouldn't matter all that match to you

Filip
  • 819
  • 1
  • 7
  • 23