Pal*_*ini 5 javascript python math python-3.x
我想要最像Pythonic的方式来舍入数字就像Javascript一样(通过Math.round()
).它们实际上略有不同,但这种差异可能会对我的应用产生巨大影响.
使用round()
Python 3中的方法:
// Returns the value 20
x = round(20.49)
// Returns the value 20
x = round(20.5)
// Returns the value -20
x = round(-20.5)
// Returns the value -21
x = round(-20.51)
Run Code Online (Sandbox Code Playgroud)
使用Math.round()
Javascript*中的方法:
// Returns the value 20
x = Math.round(20.49);
// Returns the value 21
x = Math.round(20.5);
// Returns the value -20
x = Math.round(-20.5);
// Returns the value -21
x = Math.round(-20.51);
Run Code Online (Sandbox Code Playgroud)
谢谢!
参考文献:
Jes*_*due 10
import math
def roundthemnumbers(value):
x = math.floor(value)
if (value - x) < .50:
return x
else:
return math.ceil(value)
Run Code Online (Sandbox Code Playgroud)
还没吃过我的咖啡,但是这个功能可以做你需要的.也许有一些小修改.
Python的round
功能在Python 2和Python 3之间发生了变化.但看起来您需要以下内容,它们可以在任一版本中使用:
math.floor(x + 0.5)
Run Code Online (Sandbox Code Playgroud)
这应该产生你想要的行为.