14

I need to format the number of decimal places that a variable displays in an f-string using a variable for the number of places.

n = 5
value = 0.345
print(f'{value:.4f}') 

Instead of value.4f, I need value.nf where n is the number of decimal places to which the variable should be rounded.

Mike C.
  • 1,761
  • 2
  • 22
  • 46
  • 1
    Does this answer your question? [Python3 - Use a variables inside string formatter arguments](https://stackoverflow.com/questions/28330657/python3-use-a-variables-inside-string-formatter-arguments) – Thierry Lathuille Dec 03 '19 at 13:48

1 Answers1

22

This should work:

n = 5
value = 0.345
print(f'{value:.{n}f}') 

Output:

0.34500
CDJB
  • 14,043
  • 5
  • 29
  • 55