Python中如何将6.25舍入为6.3、6.24舍入为6.2?
Python中round函数的舍入问题及解决方法
执行以下代码时:
mynum = 6.25 print(round(mynum, 1))
得到的结果是6.2,但实际需求是:
- 6.25舍入到1位小数时得到6.3
- 6.24舍入到1位小数时得到6.2
- 6.26这类数值能正常向上舍入为6.3
问题原因
Python内置的round()函数采用的是银行家舍入法(四舍六入五成双):当舍去部分的最高位为5且后续无有效数字时,会将保留部分的最后一位调整为偶数。另外,6.25作为浮点数在二进制存储中是一个略小于真实值的近似值,这也导致round()处理时最终返回6.2。
解决方案
方案1:使用decimal模块实现精确四舍五入
decimal模块可以精确处理十进制数值,支持多种舍入模式,其中ROUND_HALF_UP就是常规的“四舍五入”规则:
from decimal import Decimal, ROUND_HALF_UP def custom_round(num, decimals): return float(Decimal(str(num)).quantize(Decimal('1.' + '0'*decimals), rounding=ROUND_HALF_UP)) # 测试示例 print(custom_round(6.25, 1)) # 输出 6.3 print(custom_round(6.24, 1)) # 输出 6.2 print(custom_round(6.26, 1)) # 输出 6.3
方案2:自定义舍入函数
通过数值放大、取整再缩小的方式实现常规舍入,适合简单场景:
def custom_round(num, decimals): multiplier = 10 ** decimals return int(num * multiplier + 0.5) / multiplier # 测试示例 print(custom_round(6.25, 1)) # 输出 6.3 print(custom_round(6.24, 1)) # 输出 6.2 print(custom_round(6.26, 1)) # 输出 6.3
注:该方法对于极端大的浮点数可能存在精度问题,此时优先选择decimal模块。
内容的提问来源于stack exchange,提问作者Mattman85208
相关产品推荐
相关产品推荐

