How to convert a float to an int in Python

Converting floating-point numbers to integers in Python requires understanding the available methods and their nuances. Python provides multiple built-in functions like int(), round(), floor(), and ceil() to handle this common numerical conversion task.

This guide covers essential conversion techniques, practical tips, and real-world applications with code examples created using Claude, an AI assistant built by Anthropic. You'll learn reliable methods to handle decimal numbers effectively.

Basic conversion using int()

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

The int() function truncates floating-point numbers by removing all decimal places without rounding. In the example, 10.7 becomes 10 because int() simply discards everything after the decimal point.

This behavior makes int() particularly useful when you need predictable integer conversion without any rounding logic. However, developers should consider this carefully since truncation might not always align with mathematical expectations.

  • Works consistently with both positive and negative numbers
  • Performs faster than rounding functions
  • Maintains a clear, predictable conversion pattern

Standard conversion methods

Beyond int()'s basic truncation, Python's math module provides floor(), ceil(), and round() functions for more sophisticated integer conversions that match different mathematical needs.

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)
10.7
10

The math.floor() function consistently rounds floating-point numbers down to the nearest integer. When applied to 10.7, it returns 10 because that's the largest integer less than or equal to the input value.

  • Works reliably with both positive and negative numbers
  • Returns a float type by default. That's why we wrap it with int() for explicit integer conversion
  • Particularly useful when you need to ensure numbers are always rounded downward

This approach differs from basic truncation because it handles negative numbers more predictably. For example, math.floor(-3.7) returns -4 instead of -3.

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)
10.2
11

The math.ceil() function rounds floating-point numbers up to the nearest integer. When you pass 10.2 to math.ceil(), it returns 11.0 because that's the smallest integer greater than or equal to the input value.

  • Returns a float by default. Wrapping with int() ensures an integer output
  • Consistently rounds up regardless of decimal value. Even 10.1 becomes 11
  • Handles negative numbers predictably. For example, -3.2 rounds to -3

This method proves especially useful in scenarios where you need to ensure sufficient capacity or resources. Think of calculating storage space or determining the number of containers needed to hold items.

Using round() for nearest integer

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

The round() function follows standard mathematical rounding rules. For decimal numbers exactly halfway between two integers (like 10.5), Python rounds to the nearest even integer. This explains why 10.5 rounds to 10 instead of 11.

  • Numbers with decimals below .5 round down (10.4 becomes 10)
  • Numbers with decimals above .5 round up (10.6 becomes 11)
  • The even rounding rule prevents statistical bias in large datasets

Wrapping round() with int() ensures the output is an integer type. This combination provides a reliable way to handle decimal numbers when you need balanced rounding behavior.

Advanced techniques

Beyond the standard conversion methods, Python offers specialized techniques for handling number bases, division-based truncation, and high-performance array operations that unlock more advanced float-to-integer transformations.

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)
0b101010 0x2a

Python's bin() and hex() functions transform integers into their binary and hexadecimal string representations. When converting floating-point numbers using these functions, Python first truncates the decimal portion through int() conversion.

  • The bin() function adds the 0b prefix to indicate a binary number. For example, 42 becomes 0b101010
  • The hex() function adds the 0x prefix for hexadecimal notation. The number 42 converts to 0x2a
  • These conversions prove useful when working with bit operations or formatting numbers for specific data protocols

Remember that attempting to convert floating-point numbers directly with bin() or hex() will raise a TypeError. Always convert to integer first using any of the previously discussed methods.

Using integer division for truncation

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

Integer division with the // operator provides another way to convert floats to integers. When dividing by 1, this operator removes decimal places while considering the number's direction on the number line.

  • For positive numbers, // behaves similarly to int(). The expression 10.7 // 1 yields 10
  • With negative numbers, // rounds down to the next lowest integer. This means -10.7 // 1 produces -11
  • The additional int() wrapper ensures the result type is explicitly an integer rather than a float

This method particularly shines when working with numerical algorithms that require consistent downward rounding behavior across both positive and negative numbers.

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)
[12.34 56.78 90.12 34.56]
[12 56 90 34]

NumPy's array conversion capabilities streamline the process of transforming multiple floating-point numbers simultaneously. The astype() method efficiently converts entire arrays to a specified data type without writing loops or additional functions.

  • The np.array() function creates a NumPy array from a Python list
  • Using astype(np.int32) converts all elements to 32-bit integers while truncating decimal places
  • This approach processes large datasets much faster than converting individual elements

NumPy's array operations prove especially valuable when working with data science applications or processing large numerical datasets. The method maintains Python's standard truncation behavior but applies it uniformly across all array elements in a single operation.

Converting prices for currency display

Financial applications often need to split floating-point prices into separate dollar and cent components for proper currency formatting—the int() function enables clean separation of the whole and fractional parts while maintaining precise control over display options.

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 code demonstrates a practical way to split a decimal price into its dollar and cent components. The int(price) extracts just the whole dollar amount by truncating decimals. To get cents, we subtract the dollars from the original price and multiply by 100 before converting to an integer.

The final line showcases Python's advanced string formatting. The :02d format specifier ensures cents always display as two digits. This matters when handling values like $5.09 where we need that leading zero.

  • Input of 29.95 produces dollars = 29 and cents = 95
  • The f-string syntax makes the output clean and readable
  • This approach prevents floating-point precision issues that can affect financial calculations

Categorizing temperature readings with int()

Medical applications often use int() to simplify temperature readings for quick patient assessment, enabling healthcare providers to efficiently categorize fever levels by discarding decimal precision when exact measurements aren't critical.

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 efficient temperature classification using two key Python features: list manipulation and string formatting. The first loop evaluates each temperature reading and assigns a category based on integer thresholds, storing results in the categories list.

The second loop employs zip() to pair original temperatures with their categories, creating a detailed output string. Python's f-strings enable clear data presentation by combining floating-point temperatures, their integer conversions, and category labels.

  • Integer conversion simplifies temperature comparison logic
  • The zip() function elegantly combines two lists for parallel processing
  • F-strings format the output with both original and converted values

Common errors and challenges

Converting floating-point numbers to integers in Python requires careful attention to common pitfalls that can affect string handling, negative numbers, and decimal precision.

Handling string to integer conversion with int()

Converting strings containing decimal points directly to integers with int() raises a ValueError. The function cannot automatically handle decimal strings. The code below demonstrates this common mistake when processing user input or data from external sources.

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

The int() function can't directly parse strings containing decimal points. It expects either a whole number string or a float value. Let's examine the corrected approach in the next code block.

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

The solution chains float() and int() functions to properly handle string-to-integer conversion. First, float() parses the decimal string into a floating-point number. Then int() truncates the decimal places to create an integer.

  • Always validate string inputs before conversion to prevent runtime errors
  • Watch for regional number formats that use commas instead of decimal points
  • Consider using try-except blocks when handling user input or external data

This pattern appears frequently when processing CSV files, API responses, or user inputs. The two-step conversion ensures reliable handling of decimal strings while maintaining precise control over the final integer output.

Understanding how int() works with negative numbers

The int() function's behavior with negative numbers often surprises developers who expect mathematical rounding. When converting negative floating-point numbers, int() truncates toward zero instead of rounding down. The following example demonstrates this crucial distinction.

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

The code demonstrates how int() truncates negative numbers toward zero rather than following mathematical rounding rules. This behavior can lead to unexpected results when developers assume standard rounding. The next example shows the proper approach.

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

The math.floor() function provides more predictable behavior than int() when handling negative numbers. While int(-2.7) truncates toward zero to produce -2, math.floor(-2.7) consistently rounds down to -3. This distinction matters in financial calculations, coordinate systems, and statistical analysis.

  • Always test negative number handling explicitly in your code
  • Consider using math.floor() when you need consistent downward rounding
  • Watch for edge cases near zero where truncation and rounding differ significantly

Avoiding floating-point precision errors when converting

Python's floating-point arithmetic can produce unexpected results when converting decimals to integers. Simple operations like adding 0.1 and 0.2 introduce tiny precision errors that compound during integer conversion. The code below demonstrates this common challenge.

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

Binary floating-point representation causes 0.1 + 0.2 to equal approximately 0.30000000000000004 instead of exactly 0.3. This tiny discrepancy creates unexpected integer results when multiplying by 10. The following code demonstrates a reliable 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}")

The Decimal class from Python's decimal module provides exact decimal arithmetic that eliminates floating-point precision errors. Unlike standard floating-point math, Decimal objects maintain precise decimal places during calculations.

  • Use Decimal when working with financial data or calculations requiring exact decimal precision
  • Watch for scenarios involving multiplication or division of floating-point numbers before integer conversion
  • Pay special attention when processing currency values or percentages that need accurate decimal handling

This solution ensures reliable integer conversion by preventing the accumulation of tiny floating-point inaccuracies that could affect your final results.

FAQs

What happens to the decimal part when converting a float to int?

When converting a float to an integer, the decimal portion gets truncated—the number simply drops everything after the decimal point. This happens because integers can only store whole numbers, not fractional values.

The computer doesn't round the number up or down. For example, converting 3.9 to an integer yields 3, while -3.1 becomes -3. This behavior stems from how computers store integers in memory using a fixed number of bits that can only represent whole numbers.

Can you convert a float string like '3.14' directly to an integer?

No, you can't directly convert a float string like '3.14' to an integer. The string must first be converted to a float using float(), then to an integer using int(). This two-step process ensures proper handling of the decimal point.

Python enforces this requirement to prevent ambiguity and potential data loss. A direct string-to-integer conversion of decimal numbers would raise a ValueError since integers can't contain decimal points.

What's the difference between int() and math.floor() when converting floats?

The int() function truncates decimal numbers by simply removing everything after the decimal point. In contrast, math.floor() rounds down to the nearest integer that's less than or equal to the input. This creates an important difference with negative numbers: int(-3.7) gives -3 while math.floor(-3.7) yields -4.

The distinction matters most when processing financial calculations, game physics, or any application where consistent rounding behavior for negative values is crucial.

How do you handle float conversion errors when the value is too large?

When a float value exceeds the maximum limit, Python raises an OverflowError. You can handle this by implementing a try-except block to catch the error and provide fallback behavior. The float type follows IEEE-754 standards, which means it can only represent numbers between approximately ±1.8 × 10^308.

  • First, attempt the float conversion within a try block
  • Catch OverflowError in the except block
  • Return an alternative value or handle the error based on your application's needs

This approach maintains data integrity while preventing program crashes when processing extremely large numbers.

Is there a way to round a float before converting it to an integer?

Python's built-in round() function handles this elegantly. When you call round() on a float, it returns the nearest integer value as a float. You can then convert this rounded result to an integer using int().

The process works in two steps: first rounding the decimal places, then converting to a whole number. This approach gives you more control than directly converting a float to an integer, which simply truncates decimal places.

🏠