在 Python 2.7 中四舍五入到两位小数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17470883/
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
Rounding to two decimal places in Python 2.7?
提问by RCN
Using Python 2.7 how do I round my numbers to two decimal places rather than the 10 or so it gives?
使用 Python 2.7 如何将我的数字四舍五入到两位小数而不是它给出的 10 左右?
print "financial return of outcome 1 =","$"+str(out1)
回答by Ashwini Chaudhary
Use the built-in function round()
:
使用内置函数round()
:
>>> round(1.2345,2)
1.23
>>> round(1.5145,2)
1.51
>>> round(1.679,2)
1.68
Or built-in function format()
:
或内置函数format()
:
>>> format(1.2345, '.2f')
'1.23'
>>> format(1.679, '.2f')
'1.68'
Or new style string formatting:
或新样式字符串格式:
>>> "{:.2f}".format(1.2345)
'1.23
>>> "{:.2f}".format(1.679)
'1.68'
Or old style string formatting:
或旧式字符串格式:
>>> "%.2f" % (1.679)
'1.68'
help on round
:
帮助round
:
>>> print round.__doc__
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
回答by John Doe
print "financial return of outcome 1 = $%.2f" % (out1)
回答by TerryA
You can use str.format()
, too:
您也可以使用str.format()
:
>>> print "financial return of outcome 1 = {:.2f}".format(1.23456)
financial return of outcome 1 = 1.23
回答by teewuane
When working with pennies/integers. You will run into a problem with 115 (as in $1.15) and other numbers.
使用便士/整数时。您将遇到 115(如 1.15 美元)和其他数字的问题。
I had a function that would convert an Integer to a Float.
我有一个函数可以将整数转换为浮点数。
...
return float(115 * 0.01)
That worked most of the time but sometimes it would return something like 1.1500000000000001
.
这在大多数情况下都有效,但有时它会返回类似1.1500000000000001
.
So I changed my function to return like this...
所以我改变了我的函数来像这样返回......
...
return float(format(115 * 0.01, '.2f'))
and that will return 1.15
. Not '1.15'
or 1.1500000000000001
(returns a float, not a string)
这将返回1.15
。Not '1.15'
or 1.1500000000000001
(返回一个浮点数,而不是一个字符串)
I'm mostly posting this so I can remember what I did in this scenario since this is the first result in google.
我主要是发布这个,所以我可以记住我在这个场景中做了什么,因为这是谷歌的第一个结果。
回答by Ronan Paix?o
Since you're talking about financialfigures, you DO NOT WANTto use floating-point arithmetic. You're better off using Decimal.
既然你在谈论金融数据,你不希望使用浮点运算。最好使用十进制。
>>> from decimal import Decimal
>>> Decimal("33.505")
Decimal('33.505')
Text output formatting with new-style format()
(defaults to half-even rounding):
使用新样式的文本输出格式format()
(默认为半偶数舍入):
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.505")))
financial return of outcome 1 = 33.50
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.515")))
financial return of outcome 1 = 33.52
See the differences in rounding due to floating-point imprecision:
请参阅由于浮点不精确而导致的舍入差异:
>>> round(33.505, 2)
33.51
>>> round(Decimal("33.505"), 2) # This converts back to float (wrong)
33.51
>>> Decimal(33.505) # Don't init Decimal from floating-point
Decimal('33.50500000000000255795384873636066913604736328125')
Proper way to round financial values:
四舍五入财务价值的正确方法:
>>> Decimal("33.505").quantize(Decimal("0.01")) # Half-even rounding by default
Decimal('33.50')
It is also common to have other types of rounding in different transactions:
在不同的交易中使用其他类型的舍入也很常见:
>>> import decimal
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_DOWN)
Decimal('33.50')
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_UP)
Decimal('33.51')
Remember that if you're simulating return outcome, you possibly will have to round at each interest period, since you can't pay/receive cent fractions, nor receive interest over cent fractions. For simulations it's pretty common to just use floating-point due to inherent uncertainties, but if doing so, always remember that the error is there. As such, even fixed-interest investments might differ a bit in returns because of this.
请记住,如果您正在模拟回报结果,您可能必须在每个利息期进行四舍五入,因为您无法支付/接收美分分数,也无法获得超过美分分数的利息。对于模拟,由于固有的不确定性,通常只使用浮点数,但如果这样做,请始终记住错误就在那里。因此,即使是固定利息投资的回报也可能因此而有所不同。
回答by Thiago Santos
The best, I think, is to use the format()function:
我认为最好的方法是使用format()函数:
>>> print("financial return of outcome 1 = $ " + format(str(out1), '.2f'))
// Should print: financial return of outcome 1 = $ 752.60
But I have to say: don't use round or format when working with financial values.
但我不得不说:在处理财务价值时不要使用圆形或格式。
回答by Shan Niz
A rather simple workaround is to convert the float into string first, the select the substring of the first four numbers, finally convert the substring back to float. For example:
一个相当简单的解决方法是先将浮点数转换为字符串,然后选择前四个数字的子字符串,最后将子字符串转换回浮点数。例如:
>>> out1 = 1.2345
>>> out1 = float(str(out1)[0:4])
>>> out1
May not be super efficient but simple and works :)
可能不是超级高效但简单有效:)
回答by Midhun M M
When we use the round() function, it will not give correct values.
当我们使用 round() 函数时,它不会给出正确的值。
you can check it using, round (2.735) and round(2.725)
您可以使用 round (2.735) 和 round(2.725) 检查它
please use
请用
import math
num = input('Enter a number')
print(math.ceil(num*100)/100)
回答by Lucas VL
Rounding up to the next 0.05, I would do this way:
四舍五入到下一个 0.05,我会这样做:
def roundup(x):
return round(int(math.ceil(x / 0.05)) * 0.05,2)