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

如何使用Python将整数舍入到2位小数?,python,rounding,Python,Rounding,我在这段代码的输出中得到了很多小数(华氏到摄氏的转换器) 我的代码当前如下所示: 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:

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

我的代码当前如下所示:

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()

因此,我的问题是,如何使程序将每个答案四舍五入到小数点后第二位?

您可以使用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()

只需使用带%.2f的格式,它将四舍五入到2位小数

def printC(answer):
    print "\nYour Celsius value is %.2f C.\n" % answer
可以使用该函数,该函数的第一个参数是数字,第二个参数是小数点后的精度

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()
在您的情况下,它将是:

answer = str(round(answer, 2))
使用的显示带两位小数的
应答
(不改变
应答
的基本值):

其中:

  • 介绍
  • 0
    为数字类型启用符号感知零填充
  • .2
    将设置为
    2
  • f
    将数字显示为定点数字

因为您希望答案是十进制的,所以不需要在printC()函数中将答案变量键入str


然后使用

您可以使用round函数

round(80.23456, 3)
我的答案是80.234

在您的情况下,使用

answer = str(round(answer, 2))

你想把你的答案改圆

四舍五入(值,有效数字)
是实现这一点的普通解决方案,但是,从数学角度来看,当要四舍五入的数字的左下角有一个
5时,这种有时就不起作用了

以下是这种不可预测行为的一些示例:

>>> round(1.0005,3)
1.0
>>> round(2.0005,3)
2.001
>>> round(3.0005,3)
3.001
>>> round(4.0005,3)
4.0
>>> round(1.005,2)
1.0
>>> round(5.005,2)
5.0
>>> round(6.005,2)
6.0
>>> round(7.005,2)
7.0
>>> round(3.005,2)
3.0
>>> round(8.005,2)
8.01
假设您的目的是对科学中的统计数据进行传统的四舍五入,那么这是一个方便的包装器,可以让
四舍五入
函数按预期工作,需要
导入
额外的东西,如
十进制

>>> round(0.075,2)

0.07

>>> round(0.075+10**(-2*6),2)

0.08
啊哈!基于此我们可以做一个函数

def roundTraditional(val,digits):
   return round(val+10**(-len(str(val))-1), digits)
基本上,这会给字符串添加一个非常小的值,以迫使它在不可预测的实例上正确地进行取整,而在这种情况下,当您期望它时,它通常不会使用
round
函数进行取整。一个方便添加的值是
1e-X
,其中
X
是您试图在plus
1
上使用的
round
数字字符串的长度

使用
10**(-len(val)-1)
的方法是经过深思熟虑的,因为它是可以用来强制移位的最大小数,同时还可以确保即使缺少小数
,您添加的值也不会改变舍入。我可以使用
10**(-len(val))
和条件
if(val>1)
来减去
1
更多。。。但是总是减去
1
更简单,因为这不会改变此解决方案可以正确处理的十进制数的适用范围。如果您的值达到类型的限制,这种方法将失败,但对于几乎整个有效的十进制值范围,它应该可以工作

因此,完成的代码将类似于:

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

def roundTraditional(val,digits):
    return round(val+10**(-len(str(val))-1))

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(roundTraditional(answer,2))
    print "\nYour Celsius value is " + answer + " C.\n"

main()
…应该给你你期望的结果

您也可以使用库来实现这一点,但我建议的包装器更简单,在某些情况下可能更受欢迎



编辑:感谢您指出
5
边缘框仅适用于某些值。

大多数答案建议
圆形
格式
round
有时会向上取整,在我的例子中,我需要将变量的值向下取整,而不仅仅是这样显示

round(2.357, 2)  # -> 2.36
我在这里找到了答案:

或:


下面是我使用的一个示例:

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)

不知道为什么,但是“{:0.2f}”。格式(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
def天花板地板(x):
输入数学
如果x<0,则返回math.ceil(x),否则返回math.floor(x)
def四舍五入数字(x,n):
输入数学
返回天花板楼层(x*math.pow(10,n))/math.pow(10,n)
四舍五入数字(-0.5357706,2)->-0.53
四舍五入数字(0.5357706,2)->0.53

答案来自:

您可以使用四舍五入运算符,最多可使用2位小数

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

如果您需要避免浮点问题对会计数字进行舍入,您可以使用numpy round

您需要安装numpy:

pip install numpy
以及守则:

import numpy as np

print(round(2.675, 2))
print(float(np.round(2.675, 2)))
印刷品

2.67
2.68

如果你用合法的四舍五入来管理资金,你应该使用它。

如果你不仅需要四舍五入结果,还需要用四舍五入结果进行数学运算,那么你可以使用
decimal.decimal


如果您只想打印出舍入的结果,可以使用Python 3.6引入的。语法与的相同,只是在文本字符串前面放了一个
f
,并将变量直接放在字符串中的花括号内

.2f
表示四舍五入到小数点后两位:

number = 3.1415926
print(f"The number rounded to two decimal places is {number:.2f}")
输出:

The number rounded to two decimal places is 3.14

为了避免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

关于你的代码的一个小评论。没有理由将华氏值保持为全局值,将其作为参数传输到函数就足够了(而且更好)。所以,去掉“全球华氏温度”这一行。在formeln函数中,将参数重命名为函数“Fahreinheit”formeln(Fahreinheit)。至于四舍五入,您可以只使用“%”参数来显示前两位数字,并且应该对这些数字进行四舍五入。“我不确定是什么诱使人们对上述评论投赞成票。请注意,
round(2.675,2)
给出的是
2.67
而不是
2.68
,这一事实与银行取整无关。注意:这会改变答案的值。如果你只是想转圈展示一下,那就用@Johnsyweb-@Johnsyweb的答案吧,我正在尝试
2.67
2.68
from decimal import Decimal, ROUND_DOWN

Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32') 
number = 3.1415926
print(f"The number rounded to two decimal places is {number:.2f}")
The number rounded to two decimal places is 3.14
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