Python:将负数四舍五入到最接近的上 0.5
Python: Round off negative number to the nearest upper 0.5
我想使用 python 将负数四舍五入到最接近的上 0.5。
例如:
-1.2 => -1
-0.8 => -0.5
等等
如果我使用
round(number * 2) / 2.0
它 returns 我最接近的较低的 0.5(例如:-2.4 returns 我 -2.5 我想要 -2.0)
我如何在 python 中做到这一点?
你可以使用math
的ceil
方法得到你想要的。如果使用正数,请使用 floor
。
>>> import math
>>> math.ceil((-0.8*2))/2
-0.5
>>> math.ceil((-1.2*2))/2
-1.0
>>> math.ceil((-2.4*2))/2
-2.0
我想使用 python 将负数四舍五入到最接近的上 0.5。
例如:
-1.2 => -1
-0.8 => -0.5
等等
如果我使用
round(number * 2) / 2.0
它 returns 我最接近的较低的 0.5(例如:-2.4 returns 我 -2.5 我想要 -2.0)
我如何在 python 中做到这一点?
你可以使用math
的ceil
方法得到你想要的。如果使用正数,请使用 floor
。
>>> import math
>>> math.ceil((-0.8*2))/2
-0.5
>>> math.ceil((-1.2*2))/2
-1.0
>>> math.ceil((-2.4*2))/2
-2.0