how to show Percentage in python


Question

this is my code:

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

and it show :

0.0%

but i want get 33%

what can i do.

1
149
7/31/2016 10:24:40 AM

Accepted 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%
235
5/24/2018 12:41:46 AM

There is a way more convenient 'percent'-formatting option for the .format() format method:

>>> '{:.1%}'.format(1/3.0)
'33.3%'

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon