javascript - 像 Javascript "round()"这样的 "Math.round()"的 Pythonic 方式?

标签 javascript python python-3.x math

我想要像 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/

相关文章:

python - 元组作为函数参数

python - keras 分类和二元交叉熵

Python 3 用户定义的不可变类对象

javascript - 如何使用 on() 将元素的 ID 和字符串传递给我的函数?

javascript - execCommand 给出错误

Python 和 if 语句

python - 当我需要检查它们是否用完猜测时,有没有办法从 TimeToGuess 类访问我的gueses_left变量

python - 反转字符串的前半部分和后半部分并将它们一起返回

javascript - 是否可以从另一个嵌套箭头函数访问箭头函数的参数?

不删除第一张幻灯片的 Javascript slider 添加/删除功能