Python Forum

Full Version: Formatting a Decimal to a Percentage
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
You can have a look at the format() examples.
>>> p = 0.3194933145672062
>>> f"{p}"
'0.3194933145672062'
>>> f"{p:.0%}"
'32%'
>>> f"{p:.2%}"
'31.95%'