[英]Implement half round down
Is there a way in Python to round the number up only if the fractional part is larger than a half? 只有当小数部分大于一半时,Python中是否有一种方法可以将数字四舍五入? round
and math.ceil
will do this: round
和math.ceil
会这样做:
round(X.5) => X+1
math.ceil(X.5) => X+1
however, I want this: 但是,我想要这个:
x.500...000001 => x+1
x.500...000000 => x
How to do that? 怎么做?
I have 2.7.13 python x64 我有2.7.13 python x64
math.ceil(x-0.5)
maps: 地图:
12.50 -> ceil(12.00) -> 12
12.49 -> ceil(11.99) -> 12
12.51 -> ceil(12.01) -> 13
You can do something like this: 你可以这样做:
round(X - 0.00000000001)
You will need to decide how many decimal places are appropriate, bearing in mind that floats are not exact, so for example 10000000000000000000.5 can't be represented. 您需要确定适当的小数位数,请记住浮点数不准确,因此例如10000000000000000000.5无法表示。
I found the answer as suggested by jonrsharpe to use context This is they way I used it: 我找到了jonrsharpe建议使用上下文的答案这就是我用它的方式:
from decimal import *
x =5.500000000000001 # it is the number wanted to round, however only takes 15 number after decimal for me
ctx= Context(prec=1, rounding=ROUND_HALF_DOWN)
y = ctx.create_decimal(x)
However, I do not know if it is going to work with everybody. 但是,我不知道它是否适合所有人。 probably there is a better way to put it. 可能有一个更好的方式来表达它。
import math
while True:
num=input("num: ")
num=float(num)
new_n=round(num,0)
if (float(new_n)-0.5)==num:
print(num-0.5)
else:
print(new_n)
output: 输出:
num: 4.5
4.0
num: 5.5
5.0
num: 6.6
7.0
num: 5.5001
6.0
well I had to do some thinking but this should do what you want 好吧,我不得不做一些思考,但这应该做你想要的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.