Python 中四舍五入到小数点后 2 位
我有一个初学者问题。我该如何汇总2个小数? 这是我尝试的和我想实现的目标:
import math
var_1 = 14.063 # expected = 14.06
var_2 = 10.625 # expected = 10.63
print(round(14.063, 2))
print(round(10.625, 2))
print('===========================')
def round_up(n, decimals=0):
multiplier = 10 ** decimals
return math.ceil(n * multiplier) / multiplier
print(round_up(var_1, 2))
print(round_up(var_2, 2))
输出是:
14.06
10.62
===========================
14.07
10.63
所以这些都不适合我...
I have a beginner problem. How can I round up to 2 decimal?
Here is what I tried and what I want to achieve:
import math
var_1 = 14.063 # expected = 14.06
var_2 = 10.625 # expected = 10.63
print(round(14.063, 2))
print(round(10.625, 2))
print('===========================')
def round_up(n, decimals=0):
multiplier = 10 ** decimals
return math.ceil(n * multiplier) / multiplier
print(round_up(var_1, 2))
print(round_up(var_2, 2))
And the Output is:
14.06
10.62
===========================
14.07
10.63
So neither of those wroks for me...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
十进制模块的小数类,量化()方法和round_half_up规则可以处理这一点:
我得到:
请记住,当您处理浮子时,您总是在操纵对什么比不太明确的表示什么您可能(自然地)想到了:
在第一种情况下,首先将1.65变成IEEE-754浮点,该浮点具有从Base-10到Base-2的精度错误,然后传递到十进制。在第二种情况下,十进制将数字解释为“一个和65个100-1”,相当于“ 165乘以10升至负2”或165E-2。
The Decimal class, quantize() method, and ROUND_HALF_UP rule from the decimal module can handle this:
and I get:
Keep in mind that when you're dealing with floats, you're always manipulating a less-than-precise representation of what you probably (naturally) have in mind:
In the first case, 1.65 was first turned into an IEEE-754 float, which has precision errors going from base-10 to base-2, then passed to Decimal. In the second case, Decimal interpreted the number as "one, and 65 100-ths" which equates to "165 times 10 raised to the minus 2", or 165e-2.
试试这个。这会找到最近的一个,如果没有,则向上舍入 -
Try this. This finds the nearest one and if not, then round up -
这应该有效,尽管有一种更有效的方法的方法。我只是拿走了您的代码,并确定了哪一个距离更接近,如果它们相同。
编辑:PCM似乎已经制作了这样的版本。
this should work, although there is probebly a more efficient way of doing it. I just took your code and determined which one was closer, and if they are the same to round up.
Edit: It seems that PCM has made such version.
如果您检查文档,您会看到“值将圆形到最接近的倍数到10的最接近元素,如果两个倍数同样接近,则圆形对偶数选择进行(例如,例如,两个圆形(0.5)(0.5)(0.5)圆(-0.5)为0,圆(1.5)为2)”。
因此,10.625回合至10.62。您可以尝试添加一个很小的值,例如0.00001,但即使如此,由于浮点数的工作方式,在少数情况下,您可能会感到惊讶。
If you check the docs you will see that "values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2)".
So 10.625 rounds to 10.62. You may try adding a very small value, e.g. 0.00001, but even so, since the way float numbers work, you may have some surprise in a few cases.