Floating number to percentage conversion in Python string formatting

gynDG report abuse

Hi. I perform some calculations in Python and I need to represent the result of the calculations as the percentage. It is required to substitute the value into the string (instead of a placeholder) using string.format() method. But at the moment I'm able only to replace a placeholder only with the float number, but not with the percentage. Is it possible to represent a floating-point number as a percentage when using Python's string.format() method?


PyAnto report abuse

You can use format specifiers for this task. You can find more information on Python website: https://www.python.org/dev/peps/pep-3101/ .

For example, you can run the following code:

print("{0} in percentage is {1:.0%}".format(0.25, 0.25))

Output of the above code: "0.25 in percentage is 25%"

You can control the number of signs after the comma. For example, to limit them to 2 digits:

print("Total: {0:.2%}".format(0.98758))

Ooutput: "Total: 98.76%"

Hope this helped.

gynDG report abuse

Yes, thank you!

Add Answer

Need support?

Just drop us an email to ... Show more