Formatting to number of decimals dynamically using Python

Asked

Viewed 85 times

3

import math

def formating_pi(n):
    a= "pi com {:c} casas decimais é {:.17}"
    return a.format(n, math.pi)

formating_pi(5)

I’d like to not put the number 17 explicitly, but rather the result of the expression n + 1.

However, when I try to do this, the following error is raised:

ValueError: Format specifier missing precision. 

Because the n or n + 1 are not seen as a numbers.

In this case n is 5 what is supposed to somehow result with output pi with 5 decimal places is 3.14159.

2 answers

3


One option is to create the format string dynamically and then use it in conjunction with the method format.

Sort of like this:

n = 17
fmt_str = f"{{:.{n + 1}}}"

print(fmt_str)  # {:.18}

Note that I used two opening and closing brackets ({{ and }}) so that Python does not use them for interpolation (yet).

Once the format string has been created dynamically (something, in the above example, like "{:.18}", we can pass it to the method format.

import math

n = 17
fmt_str = f"{{:.{n + 1}}}"

print(fmt_str)  # {:.18}

result = fmt_str.format(math.pi)

print(result)  # 3.14159265358979312
  • 1

    Thank you so much for the super quick reply Luiz.

  • @Ugabuga In my answer you have an option not to add 1 to n :-)

3

In the format it is possible to do so:

import math

def formating_pi(n):
    fmt = "pi com {} casas decimais é {:.{size}f}"
    return fmt.format(n, math.pi, size=n)

print(formating_pi(5)) # pi com 5 casas decimais é 3.14159

Don’t forget to put the f to indicate that it is a float (so you don’t have to add 1 to the n).

See on documentation all formatting options. With f-string would look like this:

def formating_pi(n):
    return f"pi com {n} casas decimais é {math.pi:.{n}f}"

Although, to round off to a certain number of decimal places, you can use round():

import math

def formating_pi(n):
    fmt = "pi com {} casas decimais é {}"
    return fmt.format(n, round(math.pi, n))

print(formating_pi(5)) # pi com 5 casas decimais é 3.14159

Or, with f-string:

def formating_pi(n):
    return f"pi com {n} casas decimais é {round(math.pi, n)}"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.