How to Convert Float to an Int In Python

Share This Post

Python is a versatile language that can be used for a variety of purposes. In this blog post, we will discuss how to convert float to an int in Python. This is a very common task that you may need to perform during your programming career. Let’s get started!

How to convert float to an Int

There are a few different ways to convert float to an int in Python. One way is to use the built-in function int(). This function takes any number (including float) and converts it to an integer. Let’s see how this works with a simple example:

>>> float_num = 12.34

>>> int(float_num)

12

>>> float_num = 12.99

>>> int(float_num)

12

As you can see, the int() function rounds down to the nearest integer when given float. If you want to round up or down to the nearest integer.

You can use the math module. The math module has a function called ceil() that rounds up to the nearest integer and a function called floor() that rounds down to the nearest integer. Let’s see how these work:

>>> float_num = 12.34

>>> math.ceil(float_num)

13

>>> float_num = 12.99

>>> math.floor(float_num)

12

As you can see, the math.ceil() function rounds up to the next highest integer while the math.floor() function rounds down to the next lowest integer.

These are just a few of the ways that you can convert float to an int in Python. Experiment with these methods and find the one that works best for your needs. Thanks for reading and happy coding!

Read More: How to Convert a Python String to Integers?

spot_img

Related Posts

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img