user input value to use as decimal value python

后端 未结 2 329
悲哀的现实
悲哀的现实 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:11

    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
    

提交回复
热议问题