Python是否设置不带舍入的小数位数范围?

2024-10-04 09:20:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如何获取float变量,并控制在不使用round()的情况下float的输出距离?例如。

w = float(1.678)

我要取x,然后用它做以下变量。

x = 1.67
y = 1.6
z = 1

如果我使用相应的圆方法:

x = round(w, 2) # With round I get 1.68 
y = round(y, 1) # With round I get 1.7
z = round(z, 0) # With round I get 2.0

它会把数字变圆,到我没用的地步。我知道这是圆点,它工作正常。我怎样才能得到x,y,z变量所需要的信息,并且仍然能够在其他浮点数格式的方程中使用它们呢?


Tags: 方法信息距离get格式with情况数字
3条回答

如果你只需要控制格式的精度

pi = 3.14159265
format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
format(pi, '.1f') #print 3.1
format(pi, '.10f') #print 3.1415926500, more precision than the original

如果需要控制浮点运算的精度

import decimal
decimal.getcontext().prec=4 #4 precision in total
pi = decimal.Decimal(3.14159265)
pi**2 #print Decimal('9.870') whereas '3.142 squared' would be off

--编辑--

没有“舍入”,因此截断数字

import decimal
from decimal import ROUND_DOWN
decimal.getcontext().prec=4
pi*1 #print Decimal('3.142')

decimal.getcontext().rounding = ROUND_DOWN
pi*1 #print Decimal('3.141')

一个超级简单的解决方案是使用字符串

x = float (str (w)[:-1])
y = float (str (w)[:-2])
z = float (str (w)[:-3])

任何一个浮点库的解决方案都需要你回避一些舍入,并且使用10的floor/powers来挑选小数点,与上面的相比可能会有点毛茸茸的。

你可以:

def truncate(f, n):
    return math.floor(f * 10 ** n) / 10 ** n

测试:

>>> f=1.923328437452
>>> [truncate(f, n) for n in range(7)]
[1.0, 1.9, 1.92, 1.923, 1.9233, 1.92332, 1.923328]

相关问题 更多 >