Reputation: 35680
Given a float between 0 and 1, how to print it as a percentage?
For example, 1/3
should print as 33%
.
Upvotes: 294
Views: 621747
Reputation: 188164
Since Python 3.0, str.format
and format
support a percentage presentation type:
>>> f"{1/3:.0%}"
'33%'
>>> "{:.0%}".format(1/3)
'33%'
>>> format(1/3, ".0%")
'33%'
Percentage. Multiplies the number by 100 and displays in fixed (
'f'
) format, followed by a percent sign.
The .0
part of the format spec .0%
indicates that you want zero digits of precision after the decimal point, because with f"{1/3:%}"
you would get the string '33.333333%'
.
It works with integers, floats, and decimals. See PEP 3101.
Upvotes: 433
Reputation: 1667
Just to add Python 3 f-string solution
prob = 1.0/3.0
print(f"{prob:.0%}") # 33%
print(f"{prob:.2%}") # 33.33%
Upvotes: 101
Reputation: 29
this is what i did to get it working, worked like a charm
divideing = a / b
percentage = divideing * 100
print(str(float(percentage))+"%")
Upvotes: -1
Reputation: 13726
Just for the sake of completeness, since I noticed no one suggested this simple approach:
>>> print("%.0f%%" % (100 * 1.0/3))
33%
Details:
%.0f
stands for "print a float with 0 decimal places", so %.2f
would print 33.33
%%
prints a literal %
. A bit cleaner than your original +'%'
1.0
instead of 1
takes care of coercing the division to float, so no more 0.0
Upvotes: 95
Reputation:
There is a way more convenient 'percent'-formatting option for the .format()
format method:
>>> '{:.1%}'.format(1/3.0)
'33.3%'
Upvotes: 225
Reputation: 7623
Then you'd want to do this instead:
print str(int(1.0/3.0*100))+'%'
The .0
denotes them as floats and int()
rounds them to integers afterwards again.
Upvotes: 4
Reputation: 118528
You are dividing integers then converting to float. Divide by floats instead.
As a bonus, use the awesome string formatting methods described here: http://docs.python.org/library/string.html#format-specification-mini-language
To specify a percent conversion and precision.
>>> float(1) / float(3)
[Out] 0.33333333333333331
>>> 1.0/3.0
[Out] 0.33333333333333331
>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'
>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'
A great gem!
Upvotes: 42