四舍五入到最接近的2/100

编程入门 行业动态 更新时间:2024-10-27 12:28:54
本文介绍了四舍五入到最接近的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

本文发布于:2023-06-08 23:38:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/591042.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最接近   四舍五入

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!