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

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

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函数,它的第一个参数是数字,第二个参数是小数点后的精度。

在你的情况下,它将是:

answer = str(round(answer, 2))

其他回答

float(str(round(answer, 2)))
float(str(round(0.0556781255, 2)))

你可以使用round函数。

round(80.23456, 3)

会给你80.234的答案吗

在你的情况下,使用

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

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

大多数回答是圆形或格式。round有时会四舍五入,在我的情况下,我需要我的变量的值四舍五入,而不仅仅是这样显示。

round(2.357, 2)  # -> 2.36

我在这里找到了答案:如何将浮点数四舍五入到某个小数点后的位置?

import math
v = 2.357
print(math.ceil(v*100)/100)  # -> 2.36
print(math.floor(v*100)/100)  # -> 2.35

or:

from math import floor, ceil

def roundDown(n, d=8):
    d = int('1' + ('0' * d))
    return floor(n * d) / d

def roundUp(n, d=8):
    d = int('1' + ('0' * d))
    return ceil(n * d) / d

下面是我用过的一个例子:

def volume(self):
    return round(pi * self.radius ** 2 * self.height, 2)

def surface_area(self):
    return round((2 * pi * self.radius * self.height) + (2 * pi * self.radius ** 2), 2)