我想要最 Pythonic 的方式来舍入数字,就像 Javascript 那样(通过Math.round()
)。它们实际上略有不同,但这种差异会对我的应用程序产生巨大的影响。
Using 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)
Using 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);
谢谢你!
参考:
- Mozilla 开发者网络 (MDN) 上的 Math.round() 解释 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
import math
def roundthemnumbers(value):
x = math.floor(value)
if (value - x) < .50:
return x
else:
return math.ceil(value)
还没喝咖啡,但该功能应该可以满足您的需要。也许需要一些小的修改。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)