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

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

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


当前回答

float(str(round(answer, 2)))
float(str(round(0.0556781255, 2)))

其他回答

from decimal import Decimal, ROUND_HALF_UP

# Here are all your options for rounding:
# This one offers the most out of the box control
# ROUND_05UP       ROUND_DOWN       ROUND_HALF_DOWN  ROUND_HALF_UP
# ROUND_CEILING    ROUND_FLOOR      ROUND_HALF_EVEN  ROUND_UP

our_value = Decimal(16.0/7)
output = Decimal(our_value.quantize(Decimal('.01'), 
rounding=ROUND_HALF_UP))
print output
float(str(round(answer, 2)))
float(str(round(0.0556781255, 2)))

不知道为什么,但'{:0.2f}'.format(0.5357706)给我'0.54'。 唯一适合我的解决方案(python 3.6)如下:

def ceil_floor(x):
    import math
    return math.ceil(x) if x < 0 else math.floor(x)

def round_n_digits(x, n):
    import math
    return ceil_floor(x * math.pow(10, n)) / math.pow(10, n)

round_n_digits(-0.5357706, 2) -> -0.53 
round_n_digits(0.5357706, 2) -> 0.53

截2指炎:

somefloat = 2.23134133
truncated = int( somefloat * 100 ) / 100  # 2.23

如果你不仅需要四舍五入的结果,而且还需要用四舍五入的结果进行数学运算,那么你可以使用十进制。十进制https://docs.python.org/2/library/decimal.html

from decimal import Decimal, ROUND_DOWN

Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32')