问题:如何用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()

所以我的问题是,如何使该程序四舍五入到小数点后第二位?

I am getting a lot of decimals in the output of this code (Fahrenheit to Celsius converter).

My code currently looks like this:

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

So my question is, how do I make the program round every answer to the 2nd decimal place?


回答 0

您可以使用该round函数,该函数将数字作为第一个参数,第二个参数是小数点后的精度。

在您的情况下,它将是:

answer = str(round(answer, 2))

You can use the round function, which takes as its first argument the number and the second argument is the precision after the decimal point.

In your case, it would be:

answer = str(round(answer, 2))

回答 1

使用语法,以显示 answer具有两个小数位(不改变的基础值answer):

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

哪里:

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

Using ‘s syntax to display answer with two decimal places (without altering the underlying value of answer):

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

Where:

  • : introduces the format spec
  • 0 enables sign-aware zero-padding for numeric types
  • .2 sets the precision to 2
  • f displays the number as a fixed-point number

回答 2

大多数答案建议roundformatround有时会四舍五入,就我而言,我需要将变量的四舍五入,而不仅仅是这样显示。

round(2.357, 2)  # -> 2.36

我在这里找到了答案:如何将浮点数四舍五入到小数点后一位?

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

Most answers suggested round or format. round sometimes rounds up, and in my case I needed the value of my variable to be rounded down and not just displayed as such.

round(2.357, 2)  # -> 2.36

I found the answer here: 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

or:

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

回答 3

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

回答 4

您想四舍五入。

round(value,significantDigit)是执行此操作的常规解决方案,但是,当从数字四舍五入到第一个数字(在其左侧)的下方(在其左侧)具有a时,有时这从数学角度来看并不像预期的那样起作用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函数按预期工作,并且需要import额外的功能,例如Decimal

>>> 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-Xwhere X是您要round在plus上尝试使用的数字字符串的长度1

使用该方法的目的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()

…应该给您期望的结果。

您也可以使用十进制库来完成此操作,但是我建议的包装器更简单,在某些情况下可能更受欢迎。


编辑:感谢Blckknght指出,5条纹情况仅在此处的某些值出现。

You want to round your answer.

round(value,significantDigit) is the ordinary solution to do this, however this sometimes does not operate as one would expect from a math perspective when the digit immediately inferior (to the left of) the digit you’re rounding to has a 5.

Here’s some examples of this unpredictable behavior:

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

Assuming your intent is to do the traditional rounding for statistics in the sciences, this is a handy wrapper to get the round function working as expected needing to import extra stuff like Decimal.

>>> round(0.075,2)

0.07

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

0.08

Aha! So based on this we can make a function…

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

Basically this adds a really small value to the string to force it to round up properly on the unpredictable instances where it doesn’t ordinarily with the round function when you expect it to. A convenient value to add is 1e-X where X is the length of the number string you’re trying to use round on plus 1.

The approach of using 10**(-len(val)-1) was deliberate, as it the largest small number you can add to force the shift, while also ensuring that the value you add never changes the rounding even if the decimal . is missing. I could use just 10**(-len(val)) with a condiditional if (val>1) to subtract 1 more… but it’s simpler to just always subtract the 1 as that won’t change much the applicable range of decimal numbers this workaround can properly handle. This approach will fail if your values reaches the limits of the type, this will fail, but for nearly the entire range of valid decimal values it should work.

So the finished code will be something like:

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

…should give you the results you expect.

You can also use the decimal library to accomplish this, but the wrapper I propose is simpler and may be preferred in some cases.


Edit: Thanks Blckknght for pointing out that the 5 fringe case occurs only for certain values here.


回答 5

只需使用%.2f的格式,它就可以四舍五入到小数点后两位。

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

Just use the formatting with %.2f which gives you rounding down to 2 decimals.

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

回答 6

您可以使用python“%”的字符串格式运算符。“%.2f”表示小数点后两位。

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

You can use the string formatting operator of python “%”. “%.2f” means 2 digits after the decimal point.

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


回答 7

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

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

You can use round operator for up to 2 decimal

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

回答 8

您可以使用舍入功能。

round(80.23456, 3)

会给你80.234的答案

根据您的情况使用

answer = str(round(answer, 2))

希望这可以帮助 :)

You can use the round function.

round(80.23456, 3)

will give you an answer of 80.234

In your case, use

answer = str(round(answer, 2))

回答 9

如果需要避免浮点问题在舍入数字时出现,可以使用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

如果您通过合法的四舍五入管理资金,则应该使用该选项。

If you need avoid floating point problem on rounding numbers for accounting, you can use numpy round.

You need install numpy :

pip install numpy

and the code :

import numpy as np

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

prints

2.67
2.68

You should use that if you manage money with legal rounding.


回答 10

这是我使用的示例:

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)

Here is an example that I used:

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)

回答 11

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

Not sure why, but ‘{:0.2f}’.format(0.5357706) gives me ‘0.54’. The only solution that works for me (python 3.6) is the following:

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

回答 12

因为您希望答案以十进制数字表示,所以您无需将您的答案变量类型转换为printC()函数中的str。

然后使用printf样式的字符串格式

As you want your answer in decimal number so you dont need to typecast your answer variable to str in printC() function.

and then use printf-style String Formatting


回答 13

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

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

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

The answer is from: https://stackoverflow.com/a/29651462/8025086


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。