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

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

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


当前回答

不知道为什么,但'{:0.2f}'.format(0.5357706)给我'0.54'。 唯一适合我的解决方案(python 3.6)如下:

def ceil_floor(x):
    import math
    return math.ceil(x) if x < 0 else math.floor(x)

def round_n_digits(x, n):
    import math
    return ceil_floor(x * math.pow(10, n)) / math.pow(10, n)

round_n_digits(-0.5357706, 2) -> -0.53 
round_n_digits(0.5357706, 2) -> 0.53

其他回答

如果你只想输出四舍五入的结果,你可以使用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
round(12.3956 - 0.005, 2)  # minus 0.005, then round.

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

您可以使用四舍五入运算符最多为2小数

num = round(343.5544, 2)
print(num) // output is 343.55

你可以使用round函数。

round(80.23456, 3)

会给你80.234的答案吗

在你的情况下,使用

answer = str(round(answer, 2))

使用str.format()的语法显示两个小数点后的答案(不改变答案的底层值):

def printC(answer):
    print("\nYour Celsius value is {:0.2f}ºC.\n".format(answer))

地点:

:介绍格式规范 0为数字类型启用可识别符号的零填充 .2将精度设置为2 F将该数字显示为一个定点数