我想要像 Javascript 一样(通过 Math.round()
)以最 Pythonic 的方式对数字进行舍入。它们实际上略有不同,但这种差异会对我的应用程序产生巨大影响。
使用 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);
谢谢!
引用资料:
最佳答案
import math
def roundthemnumbers(value):
x = math.floor(value)
if (value - x) < .50:
return x
else:
return math.ceil(value)
还没喝咖啡,但该功能应该可以满足您的需求。也许有一些小的修改。
关于javascript - 像 Javascript "round()"这样的 "Math.round()"的 Pythonic 方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34876585/