Python设置小数位范围而不舍入? [英] Python setting Decimal Place range without rounding?
问题描述
如何获取浮点变量,并在不使用 round() 的情况下控制浮点数的距离?例如.
w = float(1.678)
我想取出 x 并从中生成以下变量.
x = 1.67y = 1.6z = 1
如果我使用各自的圆形方法:
x = round(w, 2) # round 我得到 1.68y = round(y, 1) # round 我得到 1.7z = round(z, 0) # round 我得到 2.0
它会将数字四舍五入并更改到对我没有用处的程度.我明白这是圆形的重点,它可以正常工作.我将如何在 x、y、z 变量中获取我需要的信息,并且仍然能够以浮点格式在其他方程中使用它们?
您可以:
def truncate(f, n):返回 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]How can I take a float variable, and control how far out the float goes without round()? For example.
w = float(1.678)
I want to take x and make the following variables out of it.
x = 1.67
y = 1.6
z = 1
If I use the respective round methods:
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
It's going to round and alter the numbers to the point where there no use to me. I understand this is the point of round and its working properly. How would I go about getting the information that I need in the x,y,z variables and still be able to use them in other equations in a float format?
You can do:
def truncate(f, n):
return math.floor(f * 10 ** n) / 10 ** n
testing:
>>> 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]
这篇关于Python设置小数位范围而不舍入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!