如何用Python舍入到2位小数?

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


我的代码当前如下所示:


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()

所以我的问题是,如何使该程序四舍五入到小数点后第二位?


慕后森
浏览 758回答 4
4回答

慕标5151211

round是四舍六入五平分...不是严格的四舍五入例如:    round(2.135, 2)=2.13    round(2.145, 2)=2.15如果要考虑四舍五入的话,可以用quantize如:    Decimal('2.135').quantize(Decimal('0.00'))=2.14    Decimal('2.145').quantize(Decimal('0.00'))=2.15同时可以传递额外参数决定进位方式:    Decimal('2.135').quantize(Decimal('0.00'),ROUND_HALF_EVENT)=2.14    //四舍五入进位    Decimal('2.135').quantize(Decimal('0.00'),ROUND_UP)=2.14    //进位    Decimal('2.135').quantize(Decimal('0.00'),ROUND_DOWN)=2.13    //不进位更多参数可以网上自行查阅一下

慕侠2389804

您可以使用round函数,该函数将数字作为第一个参数,第二个参数作为精度。在您的情况下,它将是:answer = str(round(answer, 2))

白衣染霜花

使用str.format()的语法,以显示 answer具有两个小数位(不改变的基础值answer):def printC(answer):    print "\nYour Celsius value is {:0.2f}ºC.\n".format(answer)哪里::介绍格式规范0 为数字类型启用符号感知零填充.2将精度设置为2f 将数字显示为定点数字

胡说叔叔

大多数答案建议round或format。round有时会四舍五入,在我的情况下,我需要将变量的值四舍五入,而不仅仅是这样显示。round(2.357, 2)  # -> 2.36import mathv = 2.357print(math.ceil(v*100)/100)  # -> 2.36print(math.floor(v*100)/100)  # -> 2.35要么:from math import floor, ceildef roundDown(n, d=8):    d = int('1' + ('0' * d))    return floor(n * d) / ddef roundUp(n, d=8):    d = int('1' + ('0' * d))    return ceil(n * d) / d
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python