Convert Float to Int in Python

Posted on
How to convert float to int in Python

Python Tutorial

When we build a code program, we often use arithmetic operations. Be it multiplication, division, subtraction, addition and modulus. Python supports that too. At certain times, we need to manipulate the results of arithmetic operations, One of the manipulations is convert float to int in Python.

In some cases in arithmetic operations, we often get comma results. For example, when we perform operations like this:

A = 21
B = 3

C = A/B

print(C)

The result is:

7.0

Why result is float?

Why the result we get is a float? Even though the inputs A and B are Integers, the result should be an integer 7.

By default, division in Python returns a float data type.

How to convert to integer?

then how do we change the data type to integer?

The trick is to simply add the int() data type at the beginning of the variable.

Example:

A = 21
B = 3

C = int(A/B)

print(C)

When executed, the result is:

7

Convert Int to Float

To do the conversion from Int to Float, then what you do is put the float() function.

Example:

A = 21


print(A)
print(float(A))

When executed, the result is:

21
21.0

Hopefully this float to int in Python article is useful.

Leave a Reply

Your email address will not be published.