四舍五入到小数点后2位

编程入门 行业动态 更新时间:2024-10-20 09:25:51
本文介绍了四舍五入到小数点后2位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想用以下输入/输出设计一个函数 f(x:float,up:bool):

I would like to design a function f(x : float, up : bool) with these input/output:

# 2 decimals part rounded up (up = True) f(142.452, True) = 142.46 f(142.449, True) = 142.45 # 2 decimals part rounded down (up = False) f(142.452, False) = 142.45 f(142.449, False) = 142.44

现在,我了解Python的 round 内置函数,但是它将始终将 142.449 向上舍入,这不是我想要的.

Now, I know about Python's round built-in function but it will always round 142.449 up, which is not what I want.

有没有一种方法可以比用epsilons进行大量的浮点比较(容易出错)更好的pythonic方式?

Is there a way to do this in a nicer pythonic way than to do a bunch of float comparisons with epsilons (prone to errors)?

推荐答案

您是否考虑过使用 floor 和 ceil 的数学方法?

Have you considered a mathematical approach using floor and ceil?

如果您始终希望舍入为两位数,则可以将要乘以的数字预乘以100,然后将其舍入为最接近的整数,然后再除以100.

If you always want to round to 2 digits, then you could premultiply the number to be rounded by 100, then perform the rounding to the nearest integer and then divide again by 100.

from math import floor, ceil def rounder(num, up=True): digits = 2 mul = 10**digits if up: return ceil(num * mul)/mul else: return floor(num*mul)/mul

更多推荐

四舍五入到小数点后2位

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

发布评论

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

>www.elefans.com

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