如何使用Python四舍五入到2位小数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20457038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to round to 2 decimals with Python?
提问by Dolcens
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?
所以我的问题是,如何让程序将每个答案都舍入到小数点后第二位?
采纳答案by rolisz
回答by arieli
You can use the string formatting operator of python "%". "%.2f" means 2 digits after the decimal point.
您可以使用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
http://docs.python.org/2/library/stdtypes.html#string-formatting
回答by Santosh Ghimire
Just use the formatting with %.2f which gives you rounding down to 2 decimals.
只需使用带有 %.2f 的格式,即可四舍五入到小数点后两位。
def printC(answer):
print "\nYour Celsius value is %.2f C.\n" % answer
回答by Johnsyweb
Using str.format()'s syntaxto displayanswerwith two decimal places (without altering the underlying value of answer):
使用str.format()的语法,以显示answer具有两个小数位(不改变的基础值answer):
def printC(answer):
print("\nYour Celsius value is {:0.2f}oC.\n".format(answer))
Where:
在哪里:
:introduces the format spec0enables sign-aware zero-padding for numeric types.2sets the precisionto2fdisplays the number as a fixed-point number
回答by codiacTushki
As you want your answer in decimal number so you dont need to typecast your answervariable to str in printC() function.
由于您想要十进制数的答案,因此您不需要在 printC() 函数中将答案变量类型转换为 str 。
and then use printf-style String Formatting
然后使用printf 风格的字符串格式
回答by Satyaki Sanyal
You can use the round function.
您可以使用round函数。
round(80.23456, 3)
will give you an answer of 80.234
会给你80.234的答案
In your case, use
在你的情况下,使用
answer = str(round(answer, 2))
Hope this helps :)
希望这可以帮助 :)
回答by Jason R. Mick
You want to round your answer.
你想四舍五入你的答案。
round(value,significantDigit)is the ordinary solution to do this, however this sometimesdoes 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.
round(value,significantDigit)是普通的解决方案要做到这一点,但是这有时不作为人们从数学的角度期望当数字紧接下面(左侧),你要四舍五入到数字有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 roundfunction working as expected needing to importextra stuff like Decimal.
假设您的目的是对科学中的统计进行传统的舍入,这是一个方便的包装器,可以让round函数按预期工作,需要import额外的东西,如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 roundfunction when you expect it to. A convenient value to add is 1e-Xwhere Xis the length of the number string you're trying to use roundon plus 1.
基本上,这会向字符串添加一个非常小的值,以强制它在不可预测的情况下正确四舍五入,而round当您期望它时,它通常不会与函数一起使用。一个方便的价值补充的是1e-X这里X是你想使用数字串的长度round上加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 1more... but it's simpler to just always subtract the 1as 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.
使用的方法是10**(-len(val)-1)经过深思熟虑的,因为它是您可以添加的最大小数以强制移位,同时还确保即使.缺少小数点,您添加的值也不会改变舍入。我可以只10**(-len(val))使用一个条件if (val>1)来减去1更多......但总是减去更简单,1因为这不会改变这个解决方法可以正确处理的十进制数的适用范围。如果您的值达到类型的限制,则此方法将失败,这将失败,但对于几乎整个有效十进制值范围,它都应该有效。
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 decimallibrary to accomplish this, but the wrapper I propose is simpler and may be preferred in some cases.
您也可以使用十进制库来完成此操作,但我建议的包装器更简单,并且在某些情况下可能是首选。
Edit:Thanks Blckknghtfor pointing out that the 5fringe case occurs only for certain values here.
回答by Mahadi
float(str(round(answer, 2)))
float(str(round(0.0556781255, 2)))
回答by s4w3d0ff
Most answers suggested roundor format. roundsometimes rounds up, and in my case I needed the valueof my variable to be rounded down and not just displayed as such.
大多数答案建议round或format。round有时会四舍五入,在我的情况下,我需要将变量的值四舍五入,而不仅仅是这样显示。
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
回答by Patrick Hill
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)

