python string.format()_Python string.format()百分比,不取整
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%'
解決方案
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)
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%'
總結(jié)
以上是生活随笔為你收集整理的python string.format()_Python string.format()百分比,不取整的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python三引号 内部变量_pytho
- 下一篇: python中itertools gro