如何使用Python四舍五入到2位小数? [英] How to round to 2 decimals with Python?

查看:43
本文介绍了如何使用Python四舍五入到2位小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am getting a lot of decimals in the output of this code (Fahrenheit to Celsius converter).

我的代码目前是这样的:

My code currently looks like this:

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

所以我的问题是,我如何让程序将每个答案四舍五入到小数点后第二位?

So my question is, how do I make the program round every answer to the 2nd decimal place?

推荐答案

您可以使用 round 函数,它的第一个参数是数字,第二个参数是小数点后的精度.

You can use the round function, which takes as its first argument the number and the second argument is the precision after the decimal point.

在您的情况下,它将是:

In your case, it would be:

answer = str(round(answer, 2))

这篇关于如何使用Python四舍五入到2位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆