Pythonic的方式"圆()"像Javascript"Math.round()"?

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)

还没吃过我的咖啡,但是这个功能可以做你需要的.也许有一些小修改.

  • 我认为你想要`<0.5`而不是`<= 0.5`:确切的中途情况应该向上而不是向下. (4认同)

Tom*_*zes 7

Python的round功能在Python 2和Python 3之间发生了变化.但看起来您需要以下内容,它们可以在任一版本中使用:

math.floor(x + 0.5)
Run Code Online (Sandbox Code Playgroud)

这应该产生你想要的行为.

  • 请注意,此解决方案无法正确处理一些边缘情况输入:示例为"0.49999999999999994"(生成"1.0"而不是"0.0"),"5000000000000001.0"(生成"5000000000000002.0"),`-0.3 `(产生`0.0`而不是`-0.0`).如果你关心那些边缘情况,那么@ JessePardue的解决方案就更好了. (3认同)