提问人:Nicoara Antonio 提问时间:9/13/2023 最后编辑:JNevillNicoara Antonio 更新时间:9/15/2023 访问量:82
如何在Python中将浮点数截断为小数点后数?
How to truncate a floating number to a number of decimals in Python?
问:
我是 Python 学习的初学者
我知道这会四舍五入数字而不是截断:
number_float = 14.233677
print(f"{number_float:.3f}")
=>这是打印 14.234,但我想要 14.233
我还可以使用什么其他函数,或者我该如何格式化它,因为它不会四舍五入我的数字?
我尝试过这种格式,我知道这是错误的:.3f
答:
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
评论
1.2
1.1999999999999999555910790149937383830547332763671875
1.199