如何使用Python保留两位小数?

629

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

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

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


11
关于你的代码,有一个小注释。没有必要将华氏温度值作为全局变量保存,将其作为参数传递到函数中就足够了(而且更好)。因此,请删除 "global Fahrenheit" 行。 在 formeln 函数中,将参数名称改为函数 "Fahrenheit",即 formeln(Fahrenheit)。 至于舍入,您只需使用 "%" 参数来仅显示前两位数字,并且应对这些数字进行舍入。在 formeln 中提供的公式中,提供的数字位数不会受到影响。 - arieli
21个回答

9

您可以使用round运算符保留小数点后两位。

num = round(343.5544, 2)
print(num) // output is 343.55

9

只需使用格式化字符串 %.2f 即可将数字保留两位小数并向下取整。

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

5
为了避免round()函数出现意外的值,这是我的方法:
Round = lambda x, n: eval('"%.'+str(int(n))+'f" % '+repr(int(x)+round(float('.'+str(float(x)).split('.')[1]),n)))

print(Round(2, 2))       # 2.00
print(Round(2.675, 2))   # 2.68

对于0.625不起作用。 - Taras Mykhalchuk
请解释您正在尝试解决什么问题(有什么惊喜)以及你的 lambda 做了什么。 - not2qubit

5
你可以使用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


3

截断为2位小数:

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

2

这是我使用的一个例子:

def volume(self):
    return round(pi * self.radius ** 2 * self.height, 2)

def surface_area(self):
    return round((2 * pi * self.radius * self.height) + (2 * pi * self.radius ** 2), 2)

1
迄今为止,我发现最简单的解决方案是使用它,不知道为什么人们不使用它。
# 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)

这是一种复杂的重新实现 "%.2f" % a 的方式。 - bfontaine

1

0
不知道为什么,但是'{: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

1
这是截断,而不是四舍五入。 - ShadowRanger
"{:0.2f} 已正确地将值四舍五入。您的解决方案未进行四舍五入。" - misantroop

0

简单示例

bill = 10.24 print(round(10.241))


2
嗨,@Savana Rohit,这个答案与其他答案重复了。感谢您的贡献!您的答案没有问题,但其他人已经提供了这个答案。我建议删除这个答案。 - TempleGuard527

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接