杰瑞科技汇

Python float转int如何正确处理小数?

Of course! Converting a Python float to an int is a common task, but it's important to understand the different methods and their behaviors, as they can produce different results.

Python float转int如何正确处理小数?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the main ways to convert, from the most common to more specific use cases.

The Basic Conversion: int()

The most straightforward way to convert a float to an int is by using the built-in int() function. This function truncates the number, which means it simply cuts off (or discards) the decimal part.

How it works:

  • For positive numbers, it rounds down.
  • For negative numbers, it rounds up (towards zero).

Examples:

# --- Positive Numbers ---
positive_float = 8.9
positive_int = int(positive_float)
print(f"Converting {positive_float} to int gives: {positive_int}")  # Output: 8
positive_float_2 = 8.1
positive_int_2 = int(positive_float_2)
print(f"Converting {positive_float_2} to int gives: {positive_int_2}") # Output: 8
# --- Negative Numbers ---
negative_float = -8.9
negative_int = int(negative_float)
print(f"Converting {negative_float} to int gives: {negative_int}")  # Output: -8
negative_float_2 = -8.1
negative_int_2 = int(negative_float_2)
print(f"Converting {negative_float_2} to int gives: {negative_int_2}") # Output: -8

Key Takeaway: int() always truncates towards zero. It does not round to the nearest integer.

Python float转int如何正确处理小数?-图2
(图片来源网络,侵删)

Rounding to the Nearest Integer: round()

If you want to round the float to the nearest integer (and then convert it), you should use the round() function.

How it works:

  • Rounds to the nearest integer.
  • If the decimal part is .5, it rounds to the nearest even integer. This is called "bankers' rounding" and helps reduce bias in statistical calculations.

Examples:

# --- Numbers with decimal < .5 ---
float_1 = 8.3
rounded_1 = round(float_1)
print(f"Rounding {float_1} gives: {rounded_1}")  # Output: 8
# --- Numbers with decimal > .5 ---
float_2 = 8.7
rounded_2 = round(float_2)
print(f"Rounding {float_2} gives: {rounded_2}")  # Output: 9
# --- Numbers with decimal == .5 (Bankers' Rounding) ---
float_3 = 7.5  # Nearest even integer is 8
rounded_3 = round(float_3)
print(f"Rounding {float_3} gives: {rounded_3}")  # Output: 8
float_4 = 8.5  # Nearest even integer is 8
rounded_4 = round(float_4)
print(f"Rounding {float_4} gives: {rounded_4}")  # Output: 8

Important Note: The round() function returns a float if the input is a float. If you need an int, you must convert it again.

my_float = 9.8
result = round(my_float)
print(f"Type of result: {type(result)}")  # Output: <class 'float'>
# To get an int, you can do:
result_as_int = int(round(my_float))
print(f"Type of result_as_int: {type(result_as_int)}") # Output: <class 'int'>

Rounding Up: math.ceil()

If you always want to round a number up to the next highest integer, you can use the math.ceil() function (ceiling).

Python float转int如何正确处理小数?-图3
(图片来源网络,侵删)

How it works:

  • math.ceil(8.1) -> 9
  • math.ceil(8.9) -> 9
  • math.ceil(-8.1) -> -8 (Rounds up towards zero)

Setup:

You first need to import the math module.

import math
# --- Positive Numbers ---
float_1 = 8.1
ceil_1 = math.ceil(float_1)
print(f"Ceiling of {float_1} is: {ceil_1}")  # Output: 9
float_2 = 8.9
ceil_2 = math.ceil(float_2)
print(f"Ceiling of {float_2} is: {ceil_2}")  # Output: 9
# --- Negative Numbers ---
float_3 = -8.1
ceil_3 = math.ceil(float_3)
print(f"Ceiling of {float_3} is: {ceil_3}")  # Output: -8

Note: math.ceil() also returns a float. You'll need to cast it to int if you need an integer type.


Rounding Down: math.floor()

If you always want to round a number down to the next lowest integer, you can use the math.floor() function (floor).

How it works:

  • math.floor(8.1) -> 8
  • math.floor(8.9) -> 8
  • math.floor(-8.1) -> -9 (Rounds down away from zero)

Setup:

You first need to import the math module.

import math
# --- Positive Numbers ---
float_1 = 8.1
floor_1 = math.floor(float_1)
print(f"Floor of {float_1} is: {floor_1}")  # Output: 8
float_2 = 8.9
floor_2 = math.floor(float_2)
print(f"Floor of {float_2} is: {floor_2}")  # Output: 8
# --- Negative Numbers ---
float_3 = -8.1
floor_3 = math.floor(float_3)
print(f"Floor of {float_3} is: {floor_3}")  # Output: -9

Note: math.floor() also returns a float.


Summary Table

Method Behavior Example (9) Example (-8.9) Return Type
int() Truncates (cuts off decimal) 8 -8 int
round() Rounds to nearest integer 9 -9 float
math.ceil() Rounds Up to the next integer 0 -8.0 float
math.floor() Rounds Down to the next integer 0 -9.0 float

Which One Should You Use?

  • Use int() when you simply want to discard the decimal part, like when dealing with counts or indices where fractions don't make sense.

    # Getting the whole number of dollars from a price
    price = 19.99
    dollars = int(price) # dollars is 19
  • Use round() when you want to get the closest possible integer value to the float, which is common in financial calculations or when displaying data.

    # Calculating average score
    average_score = 85.6
    final_score = round(average_score) # final_score is 86.0 (float)
  • Use math.ceil() when you need to ensure you have enough of something. For example, if you need to ship 120 items and a box holds 10, you need math.ceil(120 / 10) = 12 boxes, not int(120 / 10) = 12 (which works here, but int(121 / 10) would give 12, while math.ceil(121 / 10) correctly gives 13).

  • Use math.floor() when you want to calculate how many whole units you can fit. For example, if you have 100 MB of data and a file is 30 MB, you can fit math.floor(100 / 30) = 3 files.

分享:
扫描分享到社交APP
上一篇
下一篇