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

2024-09-26 18:12:15 发布

您现在位置: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()

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


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将数字显示为定点数字

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

在您的情况下,它将是:

answer = str(round(answer, 2))

大多数答案建议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

相关问题 更多 >

    热门问题