我在这段代码的输出中得到了很多小数(华氏到摄氏度转换器)。

我的代码目前看起来是这样的:

def main():
    printC(formeln(typeHere()))

def typeHere():
    global Fahrenheit
    try:
        Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))
    except ValueError:
        print "\nYour insertion was not a digit!"
        print "We've put your Fahrenheit value to 50!"
        Fahrenheit = 50
    return Fahrenheit

def formeln(c):
    Celsius = (Fahrenheit - 32.00) * 5.00/9.00
    return Celsius

def printC(answer):
    answer = str(answer)
    print "\nYour Celsius value is " + answer + " C.\n"



main()

我的问题是,如何让程序把每个答案四舍五入到小数点后2位?


当前回答

round(12.3956 - 0.005, 2)  # minus 0.005, then round.

答案来自:https://stackoverflow.com/a/29651462/8025086

其他回答

简单的例子

比尔= 10.24 打印(圆(10.241))

截2指炎:

somefloat = 2.23134133
truncated = int( somefloat * 100 ) / 100  # 2.23
float(str(round(answer, 2)))
float(str(round(0.0556781255, 2)))

只需使用%格式即可。2f可以四舍五入到2个小数。

def printC(answer):
    print "\nYour Celsius value is %.2f C.\n" % answer

为了避免round()的惊人值,以下是我的方法:

Round = lambda x, n: eval('"%.'+str(int(n))+'f" % '+repr(int(x)+round(float('.'+str(float(x)).split('.')[1]),n)))

print(Round(2, 2))       # 2.00
print(Round(2.675, 2))   # 2.68