📜  在 python 中浮动到 int(1)

📅  最后修改于: 2023-12-03 15:07:46.992000             🧑  作者: Mango

在 Python 中浮点数转换成整数

在 Python 中将浮点数转换为整数,可以使用以下方法:

1. 使用 int() 函数

使用 int() 函数可以将浮点数转换为整数,但是会丢失小数部分的精度。

number = 3.14
int_number = int(number)
print(int_number)  # output: 3
2. 向下取整

使用 math.floor() 函数可以向下取整,返回小于或等于浮点数的最大整数。

import math
number = 3.99
int_number = math.floor(number)
print(int_number)  # output: 3
3. 向上取整

使用 math.ceil() 函数可以向上取整,返回大于或等于浮点数的最小整数。

import math
number = 3.01
int_number = math.ceil(number)
print(int_number)  # output: 4
4. 四舍五入

使用 round() 函数可以四舍五入,其中第二个参数可以指定小数点后保留的位数。

number = 3.456
int_number = round(number)
print(int_number)  # output: 3

number = 3.456
int_number = round(number, 1)
print(int_number)  # output: 3.5

在以上方法中,使用 int() 函数简单粗暴,能满足大部分情况的要求,但是如果需要精确到小数点后几位,需要使用其他方法。