0
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

1

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))
Sign up to request clarification or add additional context in comments.

1 Comment

'Pi rounded to {0} decimal places is {1:.{0}f}.'.format(x, myPi) also works
0

You 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

0

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.

Comments

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.