四舍五入到最接近的2/100 [英] Round float to the nearest 2/100

查看:114
本文介绍了四舍五入到最接近的2/100的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要取一个像0.405这样的数字并将其四舍五入为0.40,同时还要将0.412四舍五入为0.42.有内置功能可以做到这一点吗?

I need to take a number like 0.405 and round it to 0.40 while also rounding 0.412 to 0.42. Is there any built in function to do this?

推荐答案

通用解决方案,它允许四舍五入为任意分辨率(当然,当然不是零,而是零) (a))毫无意义.对于您的情况,您只需提供0.02作为分辨率,尽管其他值也是可能的,如测试用例所示.

A general purpose solution, this allows rounding to an arbitrary resolution (well, other than zero of course, but a resolution of zero makes little sense (a)). For your case, you just need to provide 0.02 as the resolution, though other values are possible, as shown in the test cases.

# This is the function you want.

def roundPartial (value, resolution):
    return round (value / resolution) * resolution

# All these are just test cases, the first two being your own test data.

print "Rounding to fiftieths"
print roundPartial (0.405, 0.02)
print roundPartial (0.412, 0.02)

print "Rounding to quarters"
print roundPartial (1.38, 0.25)
print roundPartial (1.12, 0.25)
print roundPartial (9.24, 0.25)
print roundPartial (7.76, 0.25)

print "Rounding to hundreds"
print roundPartial (987654321, 100)

这将输出:

Rounding to fiftieths
0.4
0.42
Rounding to quarters
1.5
1.0
9.25
7.75
Rounding to hundreds
987654300.0


(a)如果您患有需要的特殊人格障碍,请您处理这种可能性,只是要注意,您所追求的是最接近的整数倍所需的分辨率.由于最接近N的数字(对于 any N)始终为0,因此始终为0,因此可以按以下方式修改函数:


(a) If you have the particular personality disorder that requires you to handle this possibility, just be aware that you're after the closest number that is a multiple of your desired resolution. Since the closest number to N (for any N) that is a multiple of 0 is always 0, you could modify the function as follows:

def roundPartial (value, resolution):
    if resolution == 0:
        return 0
    return round (value / resolution) * resolution

或者,您可以简单地保证自己不通过零作为分辨率:-)

Alternatively, you could simply promise yourself not to pass zero as a resolution :-)

这篇关于四舍五入到最接近的2/100的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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