Format a number with a certain number of decimals

Asked

Viewed 160 times

3

How do I make the user choose the number of decimals of a number?

EX:

from math import pi

x = int(input('número de casas decimais de pi: '))

I want to be able to print on the screen pi formatted with x decimal places.

1 answer

2

You can use the constant math.pi together with the function round, which takes as a parameter a number and the number of boxes after the comma.

Ex.:

from math import pi

casas = int(input('Número de casas decimais de pi: '))
print(round(pi, casas))

Code running on Repl.it

  • i would like to print for example: 'the number pi matches 3.14 ' # pi with x decimal places clear, have to use f strings, . format or % ?

  • Anderson’s answer is the one you’re looking for then

  • You can include the call from round in f-string also: f'pi = {round(pi, casas)}'

  • but round() round, wanted type, user says he wants 4 decimal places, so I print, 'pi corresponds to 3.1415'

Browser other questions tagged

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