import math
myPi = math.pi
print('Pi rounded to {0} decimal places is {1:.2f}.'.format(2, myPi))
I am trying to modify this code by switching the .2f part by using the input function.
If I say that x=int(input("put in an integer")) and I want to change the '2' in the '.2f' part to x.. how can I do it?
Sorry for my bad description. I didn't learn python in English so it is hard for me to describe.
3 Answers 3
Try following code.
import math
myPi = math.pi
x=int(input("put in an integer"))
print('Pi rounded to {0} decimal places is {1:.{2}f}.'.format(x, myPi,x))
1 Comment
'Pi rounded to {0} decimal places is {1:.{0}f}.'.format(x, myPi) also worksYou can use the round() function.
import math
myPi = math.pi
x = int(input("put in an integer: "))
print(f"Pi rounded to {x} decimal place is {round(myPi,x)}")
Comments
You can easily use f-string formatting for this, which is generally considered the best type of string formatting:
import math
myPi = math.pi
decimals = int(input("How many decimals?"))
print(f'Pi rounded to {decimals} decimal places is {myPi:.{decimals}f}.')
That way, you can place the variablenames directly into the string. Note the f before the string. As you can see, you can use {myPi:.{decimals}f} to specify both the value and the number of decimals with f-string formatting.