首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何用Python四舍五入到2位小数?

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

Stack Overflow用户
提问于 2013-12-09 02:13:41
回答 12查看 1.2M关注 0票数 435

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

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

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

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

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2013-12-09 02:20:42

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

在您的情况下,它将是:

answer = str(round(answer, 2))
票数 740
EN

Stack Overflow用户

发布于 2020-07-24 02:49:48

如果你只想打印出四舍五入的结果,你可以使用从Python3.6开始引入的f-strings。语法与str.format()format string syntax相同,不同之处在于您将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
票数 26
EN

Stack Overflow用户

发布于 2016-06-30 13:56:44

您可以使用round函数。

round(80.23456, 3)

会给你一个80.234的答案

在您的示例中,使用

answer = str(round(answer, 2))
票数 22
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20457038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档