How to convert a float to an int in Python

Learn how to convert a float to an int in Python. You'll find different methods, real-world applications, and how to debug common errors.

How to convert a float to an int in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Tue
Feb 10, 2026
The Replit Team Logo Image
The Replit Team

To convert a float to an integer in Python is a common operation, essential for data processing and numerical tasks. Python offers built-in functions like int() for straightforward type conversion.

You'll explore various conversion techniques beyond simple truncation. You will also find practical tips, see real world applications, and get advice for debugging common errors in your code.

Basic conversion using int()

float_number = 10.7
int_number = int(float_number)
print(float_number)
print(int_number)--OUTPUT--10.7
10

The int() function provides the most direct path for converting a float to an integer. When you pass 10.7 to int(), the result is 10. This isn't rounding; it's truncation. The function simply lops off the decimal part, regardless of its value.

This behavior is crucial to understand because it always moves the number toward zero. For example, int(-10.7) would result in -10, not -11. Keeping this distinction in mind is vital for avoiding unexpected results in your calculations.

Standard conversion methods

If truncation with int() isn't what you need, you can gain more control by using functions like math.floor(), math.ceil(), and round().

Using math.floor() to round down

import math
float_number = 10.7
floor_int = int(math.floor(float_number))
print(float_number)
print(floor_int)--OUTPUT--10.7
10

The math.floor() function provides a way to consistently round down. It finds the greatest integer that is less than or equal to your float value. For a positive number like 10.7, this means it rounds down to 10, which seems similar to simple truncation.

  • The key distinction from int() becomes clear with negative numbers. For instance, math.floor(-10.7) evaluates to -11, as it's the next integer down on the number line.

Since math.floor() returns a float, you'll still wrap it in int() to get a final integer type for your variable.

Using math.ceil() to round up

import math
float_number = 10.2
ceil_int = int(math.ceil(float_number))
print(float_number)
print(ceil_int)--OUTPUT--10.2
11

For rounding up, you'll use the math.ceil() function. It finds the smallest integer that is greater than or equal to the float value. This is why math.ceil(10.2) evaluates to 11.

  • With negative numbers, its behavior is the opposite of math.floor(). For instance, math.ceil(-10.2) gives you -10, moving it closer to zero.

Just like its counterpart, math.ceil() returns a float. You'll need to cast it with int() to complete the conversion to an integer type.

Using round() for nearest integer

float_number = 10.5
rounded_int = int(round(float_number))
print(float_number)
print(rounded_int)--OUTPUT--10.5
10

The round() function rounds a float to the nearest integer, but its behavior with values ending in .5 is unique. Python 3 employs a "round half to even" strategy, which means it rounds to the nearest even integer in these cases.

  • This is why round(10.5) results in 10. If you were to round 11.5, the result would be 12.

This approach helps reduce statistical bias over large sets of numbers. Unlike the math functions, round() returns an integer when called with a single argument, so the explicit int() cast isn't strictly necessary but is harmless.

Advanced techniques

When standard conversion methods don't quite fit, you can use advanced techniques for handling number bases, arrays of floats, or even simple integer division.

Converting with different number bases

float_number = 42.9
binary_repr = bin(int(float_number))
hex_repr = hex(int(float_number))
print(binary_repr, hex_repr)--OUTPUT--0b101010 0x2a

You can convert floats to integers as an intermediate step for changing their number base. The process first truncates the float using int(), so 42.9 becomes 42. From there, you can use other built-in functions for the final conversion.

  • The bin() function takes the integer and returns its binary representation as a string, prefixed with 0b.
  • Similarly, hex() provides the hexadecimal string, prefixed with 0x.

This is a common pattern when you need to work with low-level data representations, such as in networking or hardware interaction.

Using integer division for truncation

float_number = 10.7
truncated = int(float_number // 1)
negative = int(-10.7 // 1)
print(truncated, negative)--OUTPUT--10 -11

You can also use integer division with the // operator for a different kind of truncation. This operation, known as floor division, divides a float by 1 and rounds the result down to the nearest whole number. For a positive number like 10.7, the outcome is 10, just like simple truncation.

  • The key difference appears with negative numbers. Since floor division always rounds down toward negative infinity, -10.7 // 1 evaluates to -11, which is the same behavior you'd get from math.floor().

Using NumPy for array conversions

import numpy as np
float_array = np.array([12.34, 56.78, 90.12, 34.56])
int_array = float_array.astype(np.int32)
print(float_array)
print(int_array)--OUTPUT--[12.34 56.78 90.12 34.56]
[12 56 90 34]

When you're working with arrays of numbers, especially in data science, the NumPy library is your go-to tool. Instead of looping through each float, you can convert an entire array to integers in one shot using the .astype() method. This is not only cleaner but also much faster for large datasets.

  • The conversion truncates the decimal part, just like the standard int() function, so 12.34 becomes 12.

By specifying a type like np.int32, you're also explicitly setting the data type, which gives you precise control over memory usage.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. You can take the concepts from this article and use Replit Agent to build complete apps—with databases, APIs, and deployment—directly from a description.

For instance, Replit Agent can turn the float-to-integer techniques you've learned into production-ready tools:

  • A financial modeling tool that uses round() to correctly handle currency rounding according to statistical best practices.
  • A data analysis dashboard that uses math.floor() or integer division to group continuous sensor data into discrete bins.
  • A simple unit converter that truncates measurements with int() to display results like feet and inches from a total decimal value.

Describe your app idea, and Replit Agent can write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While converting floats to integers is usually straightforward, a few common pitfalls can introduce subtle bugs into your code if you're not careful.

Handling string to integer conversion with int()

One frequent mistake is trying to convert a string representation of a float directly to an integer. For example, running int('10.7') will raise a ValueError because the function expects a string containing a whole number, not one with a decimal point.

  • To work around this, you need to perform a two-step conversion. First, convert the string to a float using float('10.7'), and then convert that result to an integer with int().

Understanding how int() works with negative numbers

The behavior of int() with negative numbers can also be a source of confusion. Because it truncates toward zero, int(-10.7) results in -10. This is different from rounding down, which would yield -11.

  • If your application requires consistently rounding down for all numbers—positive or negative—relying on int() alone will produce incorrect results for negative values. In those cases, math.floor() is the appropriate tool.

Avoiding floating-point precision errors when converting

Finally, you should be aware of floating-point precision issues. Due to how computers store decimal numbers, some floats aren't perfectly precise. A value you expect to be 12.0 might actually be stored as 11.999999999999999.

  • Applying int() to such a number would truncate it to 11, which is likely not what you intended. A simple way to mitigate this is to use round() before the conversion, as it can help handle these minor precision errors before they affect your outcome.

Handling string to integer conversion with int()

A common mistake is feeding a string that contains a decimal point directly into the int() function. Python's int() function expects a string representing a whole number, so this will immediately raise a ValueError. The following code demonstrates this exact issue.

user_input = "42.5"
integer_value = int(user_input)
print(f"Converted value: {integer_value}")

This code raises a ValueError because the int() function is strict and cannot parse a string containing a decimal point. It only recognizes characters that form a whole number. The example below shows the correct approach.

user_input = "42.5"
integer_value = int(float(user_input))
print(f"Converted value: {integer_value}")

The correct approach is a two-step conversion. You must first change the string into a float using the float() function. From there, you can apply int() to the resulting float to get your integer. This pattern is especially important when you're handling user input or data read from files, since numbers from these sources are often represented as text and can include decimals.

Understanding how int() works with negative numbers

It's easy to get tripped up by how the int() function handles negative numbers. It doesn't round down but instead truncates toward zero, which can be counterintuitive. The following code shows what happens when you convert a negative float this way.

negative_float = -2.7
rounded_int = int(negative_float)
print(rounded_int) # -2

The int() function's behavior with negative_float can be a bug if you expect rounding down. It moves the value toward zero, not negative infinity. The following code shows how to get the correct result every time.

import math
negative_float = -2.7
rounded_down = math.floor(negative_float)
print(rounded_down) # -3

If you need to consistently round down, math.floor() is the right tool. It ensures a number is always rounded toward negative infinity, which is why math.floor(-2.7) correctly results in -3.

  • This behavior is essential in financial or scientific applications where strict rounding rules prevent errors with negative values. Use it whenever you can't afford the ambiguity of truncation toward zero that comes with int().

Avoiding floating-point precision errors when converting

You might run into floating-point precision errors, a subtle but critical challenge. Computers can't always store decimal numbers with perfect accuracy, which can cause surprising results during integer conversion. The code below shows how a simple calculation can go unexpectedly wrong.

result = 0.1 + 0.2
integer_test = int(result * 10)
print(f"0.1 + 0.2 = {result}")
print(f"(0.1 + 0.2) * 10 as integer: {integer_test}")

Because of how computers store floats, 0.1 + 0.2 isn't exactly 0.3. This tiny error can cause the result of multiplying by 10 to be just under 3, leading int() to truncate it unexpectedly. Check the code below for a reliable way to handle this.

from decimal import Decimal
result = Decimal('0.1') + Decimal('0.2')
integer_test = int(result * 10)
print(f"0.1 + 0.2 = {result}")
print(f"(0.1 + 0.2) * 10 as integer: {integer_test}")

To sidestep floating-point inaccuracies, you can use Python's Decimal module. By initializing numbers as strings, like Decimal('0.1'), you preserve their exact decimal representation. This prevents the small errors that binary floats introduce, ensuring calculations like Decimal('0.1') + Decimal('0.2') yield exactly 0.3.

  • It's a vital approach in financial applications or any scenario where even the tiniest rounding error can lead to significant problems.

Real-world applications

Moving past the common pitfalls, these conversion techniques are essential for everyday applications like processing financial data and categorizing sensor readings.

Converting prices for currency display

You can use int() to truncate a price, easily separating the whole dollars from the cents for clean currency formatting.

price = 29.95
dollars = int(price)
cents = int((price - dollars) * 100)
print(f"Price: ${price}")
print(f"Dollars: {dollars}, Cents: {cents}")
print(f"Formatted: ${dollars}.{cents:02d}")

This snippet shows how to deconstruct a float price into its whole and fractional parts for display. It first uses int(price) to truncate 29.95, isolating the whole dollar amount, 29. The cents are then calculated by subtracting the dollars from the original price, multiplying by 100 to shift the decimal, and finally converting the result to an integer.

  • The final print() statement uses an f-string to reassemble the price. Notice the format specifier :02d, which ensures the cents are always padded with a leading zero for correct currency formatting.

Categorizing temperature readings with int()

The int() function is also great for binning continuous data, allowing you to group precise measurements like temperature readings into broader categories.

temperatures = [98.6, 99.2, 97.5, 100.8, 96.9]
categories = []

for temp in temperatures:
if int(temp) >= 100:
categories.append("High Fever")
elif int(temp) >= 99:
categories.append("Mild Fever")
else:
categories.append("Normal")

for temp, category in zip(temperatures, categories):
print(f"{temp}°F -> {int(temp)}°F (rounded) -> {category}")

This code demonstrates how truncating with int() can simplify conditional logic. By converting each float in the temperatures list to an integer, you can use straightforward comparisons to sort them into categories.

  • The core of the logic is the if/elif/else block, which checks the truncated integer value.
  • For instance, 99.2 is converted to 99, which correctly assigns it to the "Mild Fever" category.

Finally, the zip() function is used to pair each original temperature with its new category for a clean, readable output.

Get started with Replit

Turn your knowledge into a tool. Tell Replit Agent: "Build a unit converter for feet and inches" or "Create a script that bins sensor data into integer categories."

The agent will write the code, test for errors, and deploy your app from a simple description. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.