使用Python的方式来实现"round()"就像Javascript"Math.round()"一样? [英] Pythonic way to "round()" like Javascript "Math.round()"?

查看:74
本文介绍了使用Python的方式来实现"round()"就像Javascript"Math.round()"一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用最Python的方式对数字进行四舍五入,就像Javascript一样(通过Math.round()).它们实际上稍有不同,但是这种差异会对我的应用程序产生巨大的影响.

I want the most Pythonic way to round numbers just like Javascript does (through Math.round()). They're actually slightly different, but this difference can make huge difference for my application.

使用Python 3中的round()方法:

Using round() method from 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)

使用Javascript *中的Math.round()方法:

Using Math.round() method from 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);

谢谢!

参考:

推荐答案

import math
def roundthemnumbers(value):
    x = math.floor(value)
    if (value - x) < .50:
        return x
    else:
        return math.ceil(value)

还没有喝咖啡,但是该功能可以满足您的需求.也许会有一些小的修改.

Haven't had my coffee yet, but that function should do what you need. Maybe with some minor revisions.

这篇关于使用Python的方式来实现"round()"就像Javascript"Math.round()"一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆