5

Hi I would like to dynamically adjust the displayed decimal places of a string representation of a floating point number, but i couldn't find any information on how to do it.

E.g:

precision = 8

n = 7.12345678911

str_n = '{0:.{precision}}'.format(n)

print(str_n) should display -> 7.12345678

But instead i'm getting a "KeyError". What am i missing?

1
  • 1
    print('{0:.{1}}'.format(n, precision) Commented May 10, 2020 at 9:40

2 Answers 2

10

In addition to @Talon, for those interested in f-strings, this also works.

precision = 8
n = 7.12345678911

print(f'{n:.{precision}f}')
Sign up to request clarification or add additional context in comments.

Comments

4

You need to specify where precision in your format string comes from:

precision = 8
n = 7.12345678911
print('{0:.{precision}}'.format(n, precision=precision))

The first time, you specified which argument you'd like to be the number using an index ({0}), so the formatting function knows where to get the argument from, but when you specify a placeholder by some key, you have to explicitly specify that key.

It's a little unusual to mix these two systems, i'd recommend staying with one:

print('{number:.{precision}}'.format(number=n, precision=precision))  # most readable
print('{0:.{1}}'.format(n, precision))
print('{:.{}}'.format(n, precision))  # automatic indexing, least obvious

It is notable that these precision values will include the numbers before the point, so

>>> f"{123.45:.3}"
'1.23e+02'

will give drop drop the decimals and only give the first three digits of the number. Instead, the f can be supplied to the type of the format (See the documentation) to get fixed-point formatting with precision decimal digits.

print('{number:.{precision}f}'.format(number=n, precision=precision))  # most readable
print('{0:.{1}f}'.format(n, precision))
print('{:.{}f}'.format(n, precision))  # automatic indexing, least obvious

2 Comments

I noticed that you do have to put a f between the last two curly brackets, otherwise the string will be printed with default formatting.
Nice catch, I added an explanation to the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.