How to convert a float to an int in Python

Learn how to convert a float to an int in Python. Explore different methods, tips, real-world applications, and common error debugging.

How to convert a float to an int in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

You will often need to convert floats to integers in Python for data validation or calculations. The language provides straightforward functions to handle this common and essential programming task.

In this article, you'll learn different conversion techniques like int(). You will also discover practical tips for various scenarios, see real-world applications, and get clear advice to debug common conversion errors.

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() constructor provides the most direct method for converting a float to an integer. In the example, passing the float_number 10.7 to int() results in 10. This behavior is called truncation—the function simply discards the decimal portion, effectively rounding the number toward zero. This is a common example of casting in Python.

It's important to note that this is not mathematical rounding. Whether the float is 10.1 or 10.9, applying int() will always yield 10. This makes the function a predictable and reliable choice when you need to isolate the whole number part of a float without complex rounding rules.

Standard conversion methods

When you need more control than simple truncation, Python’s math module and built-in round() function provide more specific ways to convert floats.

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 always rounds a number down to the nearest integer. For a positive number like 10.7, it returns 10, which might seem identical to truncation. The key distinction appears when you work with negative numbers.

  • math.floor() rounds down, or away from zero, for negative values. For instance, math.floor(-10.7) yields -11.
  • This contrasts with int(), which truncates toward zero, turning -10.7 into -10.

This makes math.floor() perfect when you consistently need the integer that is less than or equal to your float.

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

The math.ceil() function is the counterpart to math.floor(), as it always rounds a number up to the next whole integer. Even with a float like 10.2, it returns 11 because it seeks the smallest integer that is greater than or equal to the input. This makes it useful when you need to ensure a value meets a minimum threshold, similar to using int() function for direct conversion.

  • For positive numbers, any decimal value causes the number to round up.
  • With negative numbers, it also rounds up—which means moving toward zero. For example, math.ceil(-10.2) results in -10.

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 finds the nearest whole number, but its behavior with numbers ending in .5 might surprise you. Python uses a "round half to even" strategy, which means it rounds to the nearest even integer to prevent statistical bias.

  • round(10.5) becomes 10 because 10 is the nearest even integer.
  • round(11.5) would become 12 for the same reason.

For all other decimal values, round() behaves as you'd typically expect, rounding up or down to the closest integer. You can also use round() for rounding to decimal places when you need more precision.

Advanced techniques

Beyond standard rounding, you can leverage integer division, handle different number bases, or use libraries like NumPy for more advanced float-to-integer conversions.

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

Python lets you represent the integer part of a float in different number bases. The process starts by truncating the float with int(). After that, you can use specific functions for the conversion.

  • The bin() function converts the integer to its binary string, which is prefixed with 0b.
  • The hex() function returns the hexadecimal string representation, prefixed with 0x.

This technique is common in low-level programming where you might interact directly with binary or hex values.

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 the floor division operator, //, for conversion. When you divide a float by 1 using //, Python rounds the result down to the nearest whole number. This behavior is identical to what you get with math.floor().

  • For a positive number like 10.7, the result is 10.
  • With a negative number like -10.7, it rounds down to -11.

This makes it a concise alternative when you specifically need to round down, not just truncate toward zero.

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]

For data science and numerical computing, the NumPy library offers a highly memory-efficient way to handle arrays. You can convert an entire array of floats to integers in a single operation using the astype() method, which creates a new array with the specified data type.

  • The conversion truncates the decimal values, similar to how the standard int() function behaves.
  • Specifying a type like np.int32 lets you control the memory size of the integers. This is particularly useful for optimizing performance with large datasets.

Move faster with Replit

Replit is an AI-powered development platform where all Python dependencies come pre-installed, so you can skip setup and start coding instantly. Instead of piecing together techniques like int() and math.floor(), you can use Agent 4 to build complete applications directly from a description.

Describe the app you want to build, and the Agent will take it from an idea to a working product. For example, you could create:

  • A budget tracker that takes floating-point expenses and rounds them to the nearest whole dollar for a simplified overview.
  • A data-cleaning utility that processes sensor readings with decimal noise, truncating the values to get an accurate integer count.
  • An inventory management tool that calculates how many full units can be packaged from a bulk supply, always rounding down.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Converting floats to integers is usually simple, but a few common pitfalls can lead to unexpected results and errors in your code.

  • Handling string to integer conversion with int()
  • The int() function can't directly parse a string that contains a decimal point. If you try to run int("10.5"), Python will raise a ValueError. The fix is a two-step process: first convert the string to a float with float(), and then cast that result to an integer, like this: int(float("10.5")).
  • Understanding how int() works with negative numbers
  • A frequent point of confusion is how int() handles negative numbers. Since it always truncates toward zero, int(-10.7) becomes -10. This can be counterintuitive if you're expecting the number to round down to -11, which is the behavior of math.floor(). Being aware of this distinction is key for calculations where the rounding direction matters.
  • Avoiding floating-point precision errors when converting
  • You might also run into subtle bugs from floating-point precision. Because of how computers store decimal numbers, a value might be represented as 2.9999999999999996 instead of 3.0. Applying int() to this number truncates it to 2, which is likely not what you intended. A reliable way to handle this is to explicitly round the number with round() before you convert it to an integer.

Handling string to integer conversion with int()

You'll often run into a ValueError when trying to convert a string that contains a decimal point. The int() function expects a string representing a whole number, so it raises an error when it encounters a character like a period.

Take a look at the code below to see this common pitfall in action.

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

This code raises a ValueError because int() can't parse a string containing a decimal point. The following example demonstrates the proper way to perform this conversion.

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

The correct approach is a two-step conversion. First, convert the string to a float with float(user_input), which successfully handles the decimal point. Then, you can safely cast that float to an integer using int(). This method is essential when working with data from external sources, especially when converting strings to float. For example, user input or file reads often provide numbers as strings that might include decimals.

Understanding how int() works with negative numbers

It's easy to get tripped up by how int() handles negative numbers. The function always truncates toward zero, which isn't the same as rounding down. This distinction is crucial for accurate calculations. The code below demonstrates this common point of confusion.

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

The result is -2 because int() simply drops the decimal, moving the number toward zero. This becomes a problem if your logic requires rounding down. The following code shows how to achieve that instead.

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

To correctly round a negative number down, use math.floor(). This function always finds the nearest integer that is less than or equal to the float, so math.floor(-2.7) correctly returns -3. This isn't the same as int(-2.7), which truncates toward zero and gives you -2. Keep this distinction in mind for financial or scientific applications where the direction of rounding is critical for accuracy.

Avoiding floating-point precision errors when converting

Floating-point arithmetic isn't always exact, which can cause subtle bugs during integer conversion. A number you expect to be precise, like 0.3, might be stored slightly differently, leading to unexpected outcomes. The following code demonstrates this common precision issue.

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}")

The sum of 0.1 and 0.2 results in a number slightly larger than 0.3 due to floating-point imprecision. While int() works here, it's unreliable and can cause unexpected truncation. Check the code below for a robust solution.

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 fix precision issues, use the Decimal type from Python's decimal module. By initializing numbers as strings, like Decimal('0.1'), you ensure calculations are exact and avoid the small errors that cause standard floats to misbehave. When you multiply the Decimal result and convert it with int(), you get the correct integer every time. This method is essential for financial applications or any system where decimal accuracy is critical.

Real-world applications

Beyond just avoiding errors, these conversion techniques are fundamental to everyday applications, from displaying prices to processing sensor data.

Converting prices for currency display

When formatting prices for display, you can use int() to separate the whole dollar amount from the cents, ensuring the currency is presented clearly.

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 a common pattern for handling currency. It breaks a floating-point price into its whole dollar and cent components for clean formatting, which is useful when formatting numbers as currency.

  • The int() function first truncates the price to get the dollars.
  • To get the cents, the code subtracts the dollars from the original price, multiplies the result by 100, and converts that to an integer.
  • The final print statement uses an f-string with {cents:02d} to ensure the cents are always shown with two digits, like $29.05 instead of $29.5.

Categorizing temperature readings with int()

You can also use int() to process raw sensor data, like floating-point temperature readings, and group them into clear 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 iterates through a list of temperatures and uses int() to simplify each reading for categorization. The function truncates the decimal, so a value like 99.2 is treated as 99.

  • The if/elif/else logic then checks this integer. For instance, since int(99.2) is 99, the code assigns it the "Mild Fever" category.

This approach allows you to group floating-point data into discrete buckets based on the whole number part, making the logic clean and straightforward for AI coding with Python.

Get started with Replit

Now, turn these conversion techniques into a real tool. Tell Replit Agent to build “a tip calculator that rounds the final bill to the nearest whole dollar” or “a data utility that truncates floating-point sensor readings to integers”.

The Agent writes the code, tests for errors, and deploys the app directly from your description. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.