Python Forum
Formatting a Decimal to a Percentage
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Formatting a Decimal to a Percentage
#1
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
Reply
#2
You can have a look at the format() examples.
Reply
#3
>>> p = 0.3194933145672062
>>> f"{p}"
'0.3194933145672062'
>>> f"{p:.0%}"
'32%'
>>> f"{p:.2%}"
'31.95%'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  print function help percentage and slash (multiple variables) leodavinci1990 3 2,417 Aug-10-2020, 02:51 AM
Last Post: bowlofred
  How to calculate unique rows column sum and percentage SriRajesh 4 3,391 Feb-12-2020, 02:21 PM
Last Post: SriRajesh
  testing for Decimal w/o importing decimal every time Skaperen 7 4,362 May-06-2019, 10:23 PM
Last Post: Skaperen
  How to calculate percentage change sum (Mean) by group SriRajesh 3 3,756 Jan-09-2019, 12:28 PM
Last Post: SriRajesh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020