Python string.format()百分比到一位小数 [英] Python string.format() percentage to one decimal place
本文介绍了Python string.format()百分比到一位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的例子中,我想格式化为1位小数,但python似乎喜欢将数字四舍五入,是否有办法让它不能凑到数字之上?
In the example below I would like to format to 1 decimal place but python seems to like rounding up the number, is there a way to make it not round the number up?
>>> '{:.1%}'.format(0.9995)
'100.0%'
>>> '{:.2%}'.format(0.9995)
'99.95%'
谢谢! :)
推荐答案
如果您想总是舍入(而不是四舍五入到最接近的精度) ,那么明确地使用 math.floor()
If you want to round down always (instead of rounding to the nearest precision), then do so, explicitly, with the math.floor()
function:
from math import floor
def floored_percentage(val, digits):
val *= 10 ** (digits + 2)
return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)
print floored_percentage(0.995, 1)
p>
Demo:
>>> from math import floor
>>> def floored_percentage(val, digits):
... val *= 10 ** (digits + 2)
... return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)
...
>>> floored_percentage(0.995, 1)
'99.5%'
>>> floored_percentage(0.995, 2)
'99.50%'
>>> floored_percentage(0.99987, 2)
'99.98%'
这篇关于Python string.format()百分比到一位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文