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

2024-04-19 18:57:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的代码当前如下所示:

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


Tags: 代码answerreturnvaluemaindefprintfahrenheit
3条回答

使用^{}syntax显示带两个小数位的answer(不改变answer的基本值):

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

其中:

  • :介绍format spec
  • 0为数值类型启用可识别符号的零填充
  • .2precision设置为2
  • f将数字显示为定点数字

大多数答案都是roundformatround有时会向上取整,在我的例子中,我需要将变量的向下取整,而不仅仅是这样显示。

round(2.357, 2)  # -> 2.36

我在这里找到了答案:How do I round a floating point number up to a certain decimal place?

import math
v = 2.357
print(math.ceil(v*100)/100)  # -> 2.36
print(math.floor(v*100)/100)  # -> 2.35

或:

from math import floor, ceil

def roundDown(n, d=8):
    d = int('1' + ('0' * d))
    return floor(n * d) / d

def roundUp(n, d=8):
    d = int('1' + ('0' * d))
    return ceil(n * d) / d

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

对你来说,应该是:

answer = str(round(answer, 2))

相关问题 更多 >