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%'
%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))
The %s signifies that you want to add string value into the string, it is also used to format numbers in a string. After writing the above code (what does %s mean in python), Ones you will print ” string “ then the output will appear as a “ Variable as string = 20 ”.
How to Format a Number as Percentage. Python f-strings have a very convenient way of formatting percentage. The rules are similar to float formatting, except that you append a % instead of f . It multiplies the number by 100 displaying it in a fixed format, followed by a percent sign.
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%'
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%'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With