如何在Python中将浮点数截断为小数点后数?

How to truncate a floating number to a number of decimals in Python?

提问人:Nicoara Antonio 提问时间:9/13/2023 最后编辑:JNevillNicoara Antonio 更新时间:9/15/2023 访问量:82

问:

我是 Python 学习的初学者

我知道这会四舍五入数字而不是截断:

number_float = 14.233677
print(f"{number_float:.3f}")

=>这是打印 14.234,但我想要 14.233

我还可以使用什么其他函数,或者我该如何格式化它,因为它不会四舍五入我的数字?

我尝试过这种格式,我知道这是错误的:.3f

Python 浮点 小数 舍入 截断

评论

2赞 chtz 9/13/2023
对于(实际上是)你想打印吗?1.21.19999999999999995559107901499373838305473327636718751.199
0赞 chux - Reinstate Monica 9/14/2023
@Nicoara安东尼奥,一般来说,大多数带有分数的浮点数不能精确地四舍五入到小数点后 N 位。浮点可以对许多(但不是所有可能的十进制值)进行精确编码。14.233 不是其中之一。即使输出是文本“14.233”,内部值也更有可能是 14.233000000000000540012479177676141262054443359375,您看到的是该数字的舍入版本。

答:

0赞 Luca Micarelli 9/13/2023 #1

你可以使用数学模块,试试这个:

import math

number_float = 14.233677
decimal_places = 3

truncated_number = math.floor(number_float * 10**decimal_places) / 10**decimal_places
print(truncated_number)
1赞 Khaliladib11 9/14/2023 #2

试试这个:

number_float = 14.233677
str_nb = str(number_float).split('.')
str_nb[1] = str_nb[1][:3]
str_nb = ".".join(str_nb)
print(str_nb)
0赞 Sam Mason 9/15/2023 #3

Python 的 decimal 模块可以帮助显示正在发生的事情,例如:

from decimal import Decimal

number_float = 14.233677

# convert and show full decimal expansion
number_decimal = Decimal(number_float)
print(number_decimal)

# truncate at three decimal digits
trunc_decimal = number_decimal.quantize(Decimal("1e-3"), "ROUND_DOWN")
# convert back to float
trunc_float = float(trunc_decimal)

# output truncated values
print(trunc_decimal, trunc_float)

# how that float value isn't quite right
print(Decimal(trunc_float))

IEEE754系统(即大多数)将输出:

14.23367700000000013460521586239337921142578125
14.233 14.233
14.233000000000000540012479177676141262054443359375

或者你可以选择简单的:

import math
trunc_float = math.trunc(number_float * 1e3) / 1e3
print(trunc_float, Decimal(trunc_float))

请注意,这给出的值与通过路由的值完全相同,但两个浮点数都不完全是 14.233。它们在第 16 位左右都是错误的,我建议阅读有关 IEEE 754 标准的信息以了解原因。decimal