Python string.format()百分比无四舍五入。

问题描述 投票:24回答:4

在下面的例子中,我想格式化到小数点后1位,但python似乎喜欢将数字四舍五入,有没有办法让它不四舍五入?

>>> '{:.1%}'.format(0.9995)
'100.0%'
>>> '{:.2%}'.format(0.9995)
'99.95%'
python floating-point string.format
4个回答
14
投票

如果你想四舍五入 始终 (而不是四舍五入到最接近的精度),然后明确地用 math.floor() 功能:

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%'

1
投票

类似这样。

def my_format(num, x):
     return str(num*100)[:4 + (x-1)] + '%'

>>> my_format(.9995, 1)
'99.9%'
>>> my_format(.9995, 2)
'99.95%'
>>> my_format(.9999, 1)
'99.9%'
>>> my_format(0.99987, 2)
'99.98%'

1
投票

在Python 3.6+中,你可以使用格式化的字符串字元,也就是f-strings。它们比 str.format. 此外,你可以使用更有效的楼层划分,而不是采用 "一刀切 "的方式。math.floor. 在我看来,这种语法也更易读。

下面将这两种方法都包括在内,以便比较。

from math import floor
from random import random

def floored_percentage(val, digits):
    val *= 10 ** (digits + 2)
    return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)

def floored_percentage_jpp(val, digits):
    val *= 10 ** (digits + 2)
    return f'{val // digits / 10 ** digits:.{digits}f}%'

values = [random() for _ in range(10000)]

%timeit [floored_percentage(x, 1) for x in values]      # 35.7 ms per loop
%timeit [floored_percentage_jpp(x, 1) for x in values]  # 28.1 ms per loop

0
投票

有几种方法,也许最简单的是

x = str(10. * 0.9995).split('.')
my_string = '%s.%s%%' % (x[0], x[1][:2])

这将确保你的小数点总是在正确的位置(对于边缘情况,如 1.00000.001)

© www.soinside.com 2019 - 2024. All rights reserved.