Fix Python – How to print a percentage value in python?

Question

Asked By – zjm1126

this is my code:

print str(float(1/3))+'%'

and it shows:

0.0%

but I want to get 33%

What can I do?

Now we will see solution for issue: How to print a percentage value in python?


Answer

format supports a percentage floating point precision type:

>>> print "{0:.0%}".format(1./3)
33%

If you don’t want integer division, you can import Python3’s division from __future__:

>>> from __future__ import division
>>> 1 / 3
0.3333333333333333

# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%

# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%

This question is answered By – miku

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0