简体   繁体   中英

user input value to use as decimal value python

I am writing a python code where I ask the user for input and then I have to use their input to give the number of decimal places for the answer to an expression.

userDecimals = raw_input (" Enter the number of decimal places you would like in the final answer: ") 

then I convert this to integer value

userDecimals = int(userDecimals)

then I write the expression, and I want the answer to have as many decimal places as the user input from UserDecimals, and I don't know how to accomplish this.

The expression is

math.sqrt(1 - xx **2)

If this isn't clear enough I will try to explain it better, but I am new to python, and I don't know how to do a lot yet.

Use string formatting and pass userDecimals to the precision part of the format specifier :

>>> import math
>>> userDecimals = 6
>>> '{:.{}f}'.format(math.sqrt(1 - .1 **2), userDecimals)
'0.994987'
>>> userDecimals = 10
>>> '{:.{}f}'.format(math.sqrt(1 - .1 **2), userDecimals)
'0.9949874371'

When formatting your print statement you can specify the number of significant figures to display. For example '%.2f' % float_value will display two decimal places. See this question for a more detailed discussion.

You want something like this:

import math

xx = .2

userDecimals = raw_input (" Enter the number of decimal places you would lik    e in the final answer: ")
userDecimals = int(userDecimals)

fmt_str = "%."+str(userDecimals)+"f"

print fmt_str % math.sqrt(1 - xx **2)

Outputs:

Enter the number of decimal places you would like in the final answer: 5
0.97980

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM