Python string.format() 没有四舍五入的百分比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17610698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:39:54  来源:igfitidea点击:

Python string.format() percentage without rounding

pythonfloating-pointstring.format

提问by Ashy

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 位,但 python 似乎喜欢四舍五入,有没有办法让它不四舍五入?

>>> '{:.1%}'.format(0.9995)
'100.0%'
>>> '{:.2%}'.format(0.9995)
'99.95%'

采纳答案by Martijn Pieters

If you want to round down always(instead of rounding to the nearest precision), then do so, explicitly, with the math.floor()function:

如果要始终向下舍入(而不是舍入到最接近的精度),请使用以下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)

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

回答by danodonovan

There are a couple of ways, maybe the easiest is

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

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

this will ensure that you always have the decimal point in the correct place (for edge cases like 1.0000or 0.001)

这将确保您始终将小数点放在正确的位置(对于像1.0000或这样的边缘情况0.001

回答by Ashwini Chaudhary

Something like this:

像这样的东西:

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

回答by jpp

With Python 3.6+, you can use formatted string literals, also known as f-strings. These are more efficient than str.format. In addition, you can use more efficient floor division instead of math.floor. In my opinion, the syntax is also more readable.

在 Python 3.6+ 中,您可以使用格式化的字符串文字,也称为 f 字符串。这些比str.format. 此外,您可以使用更高效的楼层划分来代替math.floor。在我看来,语法也更具可读性。

Both methods are included below for comparison.

两种方法都包含在下面以进行比较。

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