Home > Net >  Python round a value to 3 decimal places
Python round a value to 3 decimal places

Time:09-30

For some reasons the code below doesn't round the value to 3 decimal places but only 1. Any ideas?

for y in range(len(candidates_list)):
    analysis.write(f"\n{candidates_list[y]}: {round(percentages_list[y],3)}% ({candidates_votes[y]})")

Thanks!

CodePudding user response:

Due you are using f-strings (and thats very cool instead of old .format style ), this is not a rounding representation of the number because the previous answer gives you the right way to do it, this is a truncated representation of the number on the f strings, but this answer may help to others.

Instead of printing

f'{round(percentages_list[y],3)}'

you can do:

f'{percentages_list[y]:.2f}'

CodePudding user response:

Instead of using the round() function, use the appropriate formatting operations. This will including trailing zero digits after the decimal.

And use zip() to iterate through multiple lists in parallel, rather than list indexing.

for candidate, percentage, vote in zip(candidates_list, percentages_list, candidates_votes):
    analysis.write(f"\n{candidate}: {percentage:.3f}% ({vote}")
  • Related