2015-03-25 31 views
4

如何获取一个浮点变量,并控制浮动距离没有round()的距离?例如。Python设置小数位的范围没有舍入?

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变量中的信息,并仍然能够以浮点格式在其他方程中使用它们?

+0

'[math.floor(W * 10 ** I)/ 10 **我为i的范围(3)]' – Phylogenesis 2015-03-25 02:39:18

+0

以上评论实际上是我在这种情况下使用的。我无法接受它作为评论发布的答案。谢谢! – Branzol 2015-03-25 03:15:16

回答

8

可以执行:

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] 
+0

谢谢!长期而言,我认为这将是我项目中最好的选择! – Branzol 2015-03-25 21:12:53

0

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

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 

- 编辑 -

没有控制在格式

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 
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') 
+0

当我将pi切换到我的示例中的值时,示例的格式部分将数字四舍五入。在其他方面,我从这个例子中学到了很多东西,但四舍五入就是我想要远离的东西,我需要非圆整的数字。 – Branzol 2015-03-25 03:16:24

+0

@Branzol。你仍然在四舍五入,只是有一个不同的规则。对不起,我没有清楚地看到,你正在1.6和1.6之间“舍入”1. – SYK 2015-03-25 04:24:52

1

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

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

任何浮点库解决方案将需要你躲闪某些圆整,并使用10楼/权力来挑选出小数可以得到一个小毛毛与上面的比较。

+0

谢谢,我打算玩这个。我想格式化会产生问题,因为它变成了一个字符串,而不是一个浮点数? – Branzol 2015-03-25 03:18:42

+1

我明白你的意思了 - Python的浮点运算有时可以创建长字符串。但在这种情况下,无论如何你都会遇到小数点。一个完整性检查可以代替从开始而不是结束迭代:x = float(str(w)[:4](etc) – WakkaDojo 2015-03-25 03:22:32