How to Convert a Float to a Percentage in Python?

Estimated read time 2 min read

To convert a float to a percentage in Python, you can multiply the float by 100 and format it with the desired number of decimal places. Here’s an example:

num = 0.75
percentage = num * 100
percentage_str = "{:.2f}%".format(percentage)
print(percentage_str)  # Output: '75.00%'

In this example, num is the float that you want to convert to a percentage. We multiply it by 100 to obtain the corresponding percentage value. Then, "{:.2f}%".format(percentage) formats the percentage as a string with two decimal places and adds the percentage sign (“%”). The resulting string is assigned to the variable percentage_str.

You can adjust the number of decimal places by modifying the format specifier. For example, changing "{:.2f}%" to "{:.1f}%" would result in a single decimal place.

Alternatively, you can use formatted string literals (f-strings) introduced in Python 3.6 and above:

num = 0.75
percentage = num * 100
percentage_str = f"{percentage:.2f}%"
print(percentage_str)  # Output: '75.00%'

Here, the f-string f"{percentage:.2f}%" formats the percentage as a string with two decimal places and adds the percentage sign.

By multiplying the float by 100 and formatting it as a string with the desired number of decimal places and the “%” symbol, you can easily convert a float to a percentage representation in Python.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply