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

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

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


当前回答

round(12.3956 - 0.005, 2)  # minus 0.005, then round.

答案来自:https://stackoverflow.com/a/29651462/8025086

其他回答

如果需要避免浮点数舍入问题,可以使用numpy舍入。

你需要安装numpy:

pip install numpy

代码是:

import numpy as np

print(round(2.675, 2))
print(float(np.round(2.675, 2)))

打印

2.67
2.68

如果你用合法四舍五入管理资金,你应该使用这个。

可以使用python“%”的字符串格式化操作符。 “%。“2f”表示小数点后2位。

def typeHere():
    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(Fahrenheit):
    Celsius = (Fahrenheit - 32.0) * 5.0/9.0
    return Celsius

def printC(answer):
    print "\nYour Celsius value is %.2f C.\n" % answer

def main():
    printC(formeln(typeHere()))

main()

http://docs.python.org/2/library/stdtypes.html#string-formatting

到目前为止我发现的最简单的解决方案,不知道为什么人们不使用它。

# Make sure the number is a float
a = 2324.55555
# Round it according to your needs
# dPoints is the decimals after the point
dPoints = 2
# this will round the float to 2 digits
a = a.__round__(dPoints)
if len(str(a).split(".")[1]) < dPoints:
    # But it will only keep one 0 if there is nothing,
    # So we add the extra 0s we need
    print(str(a)+("0"*(dPoints-1)))
else:
    print(a)

使用str.format()的语法显示两个小数点后的答案(不改变答案的底层值):

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

地点:

:介绍格式规范 0为数字类型启用可识别符号的零填充 .2将精度设置为2 F将该数字显示为一个定点数

round(12.3956 - 0.005, 2)  # minus 0.005, then round.

答案来自:https://stackoverflow.com/a/29651462/8025086