Python string.format()百分比不四舍五入 [英] Python string.format() percentage without rounding

查看:351
本文介绍了Python string.format()百分比不四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,我想将其格式设置为小数点后一位,但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)

演示:

>>> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆