【发布时间】:2016-01-19 12:15:45
【问题描述】:
我想要最 Pythonic 的方式来对数字进行舍入,就像 Javascript 一样(通过Math.round())。它们实际上略有不同,但这种差异会对我的应用程序产生巨大的影响。
使用 Python 3 中的 round() 方法:
// 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)
使用来自 Javascript* 的 Math.round() 方法:
// 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);
谢谢!
参考资料:
【问题讨论】:
-
请指定您使用的python版本,因为python 2和python 3可能不同。
-
首先,为什么负面点没有任何解释?谢谢@khelwood,我会提供信息。
-
This question 及其答案可能会掩盖这种情况。
-
我已更新问题以包含 Python 版本!
-
感谢您提供链接的问题,@kazemakase。现在我明白为什么 Python3 选择以这种方式对数字进行四舍五入了。
标签: javascript python python-3.x math