本文介绍了如何将浮点数舍入到给定的精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种方法将浮点数四舍五入到给定的小数位数,但我想总是向下取整.
例如,代替
>>>回合(2.667, 2)2.67我宁愿有
>>>round_down(2.667, 2)2.66 解决方案
这样的事情应该适用于你想要做的任何数量的数字:
>>>导入数学>>>def round_down(num,digits):系数 = 10.0 ** 数字返回 math.floor(num * factor)/factor>>>round_down(2.667,2)2.66I need a way to round a float to a given number of decimal places, but I want to always round down.
For example, instead of
>>> round(2.667, 2)
2.67
I would rather have
>>> round_down(2.667, 2)
2.66
解决方案
Something like this should work for whatever number of digits you want to do:
>>> import math
>>> def round_down(num,digits):
factor = 10.0 ** digits
return math.floor(num * factor) / factor
>>> round_down(2.667,2)
2.66
这篇关于如何将浮点数舍入到给定的精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!