user input value to use as decimal value python

霸气de小男生 提交于 2019-12-02 03:03:32

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'
Farmer Joe

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!