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

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

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位?


当前回答

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

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)

其他回答

到目前为止我发现的最简单的解决方案,不知道为什么人们不使用它。

# Make sure the number is a float
a = 2324.55555
# Round it according to your needs
# dPoints is the decimals after the point
dPoints = 2
# this will round the float to 2 digits
a = a.__round__(dPoints)
if len(str(a).split(".")[1]) < dPoints:
    # But it will only keep one 0 if there is nothing,
    # So we add the extra 0s we need
    print(str(a)+("0"*(dPoints-1)))
else:
    print(a)

可以使用python“%”的字符串格式化操作符。 “%。“2f”表示小数点后2位。

def typeHere():
    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(Fahrenheit):
    Celsius = (Fahrenheit - 32.0) * 5.0/9.0
    return Celsius

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

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

main()

http://docs.python.org/2/library/stdtypes.html#string-formatting

如果你只想输出四舍五入的结果,你可以使用Python 3.6以来引入的f字符串。它的语法与str.format()的格式字符串语法相同,不同之处在于在字面值字符串前面加了一个f,并且将变量直接放在字符串中,放在花括号内。

.2f表示四舍五入到小数点后两位:

number = 3.1415926
print(f"The number rounded to two decimal places is {number:.2f}")

输出:

The number rounded to two decimal places is 3.14

如果你不仅需要四舍五入的结果,而且还需要用四舍五入的结果进行数学运算,那么你可以使用十进制。十进制https://docs.python.org/2/library/decimal.html

from decimal import Decimal, ROUND_DOWN

Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32') 

截2指炎:

somefloat = 2.23134133
truncated = int( somefloat * 100 ) / 100  # 2.23