Skip to content Skip to sidebar Skip to footer

How To Format Numbers To Two Decimals In A F String Expression?

I am trying to make this program that asks a user for their grades and displays their grades with 2 decimals. - ex. if they got a 10/15 on their Assignment it would show Assignment

Solution 1:

python supports percent as formatting option:

a3 = 7
print(f"Assignment 3:  {a3/25:.2%}")  # 'Assignment 3:  28.00%'

note that there is no need to divide by 100 when using % as format specifier.

search form percent in the Format Specification Mini-Language. more information on formatting can be obtained here: https://pyformat.info/.


Solution 2:

You can use the following syntax to denote that you want the formatting in two decimal points. - You can read more here.

{your_calculation:.2%}

The .2 in this case denotes that you want the formatting in two decimal points. If you want to increase or decrease the decimal points you can adjust accordingly.


Solution 3:

You probably should ask your second question as a separate question, but one implementation would be to create a pandas dataframe.

 import pandas as pd
 last_assignment_number = 5
 assignments = ['Assignment {}'.format(i) for i in range(1,last_assignment_number+1)]+
                 ['Tutorials','Midterm','Final Exam']
 scores = pd.DataFrame(index=assignments+['Total'],
                 columns=['score','maximum','percentage'])
 maximum_scores = [15,20,25,20,30,10,30,50]
 scores['maximum'] = maximum_scores+[sum(maximum_scores)]
 for assignment in assignments:
      scores.loc[assignment,'score']=int(input("{} (/{}):").format(assignment,scores.loc[assignment,'maximum'])
 scores.loc['Total','score']=scores.loc[assignments,'score'].sum()
 scores['percentage']=(scores['score']/scores['maximum']).apply(lambda x:f"{x:.2%}")

Post a Comment for "How To Format Numbers To Two Decimals In A F String Expression?"