Multiply an integer and a Float in Python

avatar

Borislav Hadzhiev

Last updated: Jul 9, 2022

banner

Photo from Unsplash

Multiply an integer and a Float in Python #

Use the multiplication operator to multiply an integer and a float in Python, e.g. my_int * my_float. The multiplication result will always be of type float.

main.py
my_int = input('Enter your favorite number: ') print(my_int) # 👉️ '5' my_float = 2.2 # 👇️ convert string to int result = int(my_int) * my_float print(result) # 👉️ 11.0 # 👇️ multiplying int and float always returns float print(3.3 * 5) # 👉️ 16.5

The first example uses the input() function to get an integer from the user.

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from input, converts it to a string and returns the result.

Note that the input() function always returns a string, even if the user enters a number.

You can pass the string to the int() class to convert it to an integer.

main.py
my_int = input('Enter your favorite number: ') print(my_int) # 👉️ '5' my_float = 2.2 result = int(my_int) * my_float print(result) # 👉️ 11.0

The result of multiplying a float and an integer is always going to be a float.

main.py
print(2.2 * 5) # 👉️ 11.0 print(3.3 * 5) # 👉️ 16.5

You can use the round() function if you need to round the result to N digits precision after the decimal point.

main.py
print(3.14 * 5) # 👉️ 15.700000000000001 print(3.14 * 6) # 👉️ 18.84 print(round(3.14 * 5, 1)) # 👉️ 15.7 print(round(3.14 * 6, 1)) # 👉️ 18.8

The round function takes the following 2 parameters:

NameDescription
numberthe number to round to ndigits precision after the decimal
ndigitsthe number of digits after the decimal the number should have after the operation (optional)

The round function returns the number rounded to ndigits precision after the decimal point.

If ndigits is omitted, the function returns the nearest integer.

main.py
print(3.14 * 5) # 👉️ 15.700000000000001 print(3.14 * 6) # 👉️ 18.84 print(round(3.14 * 5)) # 👉️ 16 print(round(3.14 * 6)) # 👉️ 19

If you just want to drop the decimal from the number, pass the float to the int() class.

main.py
print(int(1.1)) # 👉️ 1 print(int(1.9)) # 👉️ 1

The int class returns an integer object constructed from the provided number or string argument.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.