user input value to use as decimal value python

后端 未结 2 327
悲哀的现实
悲哀的现实 2021-01-25 02:49

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.



        
2条回答
  •  醉梦人生
    2021-01-25 03:22

    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'
    

提交回复
热议问题