Python Forum
Formatting a Decimal to a Percentage - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Formatting a Decimal to a Percentage (/thread-27405.html)



Formatting a Decimal to a Percentage - dgrunwal - Jun-05-2020

I am new to the Python formatting - is there a function to round and print a percentage from a decimal?

with open("C:\file\data.txt") as f :
for line in f :
name, values = line.split(' = ')
values = literal_eval(values)
print(f"The SUM of votes rec'd in {name} is {sum(values)}")
print(f"The MAX number of votes rec'd in {name} is {max(values)}")
print(f"The MIN number of votes rec'd in {name} is {min(values)}")
print(f"Hal received {values[0]} votes AVG: - {values[0]/sum(values)}).")


Hal received 454 items AVG: - 0.3194933145672062).

How can I format the percentage to round to make it easier to read?

Hal received 454 items AVG - 31%.

Appreciate you all,
Dave


RE: Formatting a Decimal to a Percentage - Gribouillis - Jun-05-2020

You can have a look at the format() examples.


RE: Formatting a Decimal to a Percentage - bowlofred - Jun-05-2020

>>> p = 0.3194933145672062
>>> f"{p}"
'0.3194933145672062'
>>> f"{p:.0%}"
'32%'
>>> f"{p:.2%}"
'31.95%'