Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string.format() percentage without rounding

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%' 
like image 844
Ashy Avatar asked Jul 12 '13 08:07

Ashy


People also ask

What is %d %s in Python?

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

How do you write percentages in a string in Python?

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 do you format a number to a percent in an F string?

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.


2 Answers

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%' 
like image 198
Martijn Pieters Avatar answered Sep 21 '22 22:09

Martijn Pieters


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%' 
like image 20
Ashwini Chaudhary Avatar answered Sep 22 '22 22:09

Ashwini Chaudhary