2016-12-07 156 views
2

我可能會錯過一些重要的東西,但我無法找到一種方法來'適當地'圍繞Python中的浮點數/小數點(2.7),至少保留三位小數。 「適當」我的意思是1.2225應該到1.223,1.2224應該到1.222。'正確'四捨五入到Python,到小數點後三位

我知道round不會爲在Python彩車工作,通過設計,但我似乎無法得到Decimal表現不如預期,也不是ceil功能。最好是尋找內置功能而非自定義功能解決方法,但對兩者均開放。

>>> x = 1.2225         # expected: 1.223 
>>> round(x, 3)    
1.222           # incorrect 

>>> from math import ceil 

>>> ceil(x * 1000.0)/1000.0 
1.223           # correct 
>>> y = 1.2224         # expected: 1.222 
>>> ceil(y * 1000.0)/1000.0 
1.223           # incorrect 

>>> from decimal import Decimal, ROUND_UP, ROUND_HALF_UP 

>>> x = Decimal(1.2225) 
>>> x.quantize(Decimal('0.001'), ROUND_UP) 
Decimal('1.223')         # correct 
>>> y = Decimal(1.2224) 
>>> y.quantize(Decimal('0.001'), ROUND_UP) 
Decimal('1.223')         # incorrect 

>>> y.quantize(Decimal('0.001'), ROUND_HALF_UP) 
Decimal('1.222')         # correct 
>>> x.quantize(Decimal('0.001'), ROUND_HALF_UP) 
Decimal('1.222')         # incorrect 

有沒有辦法得到想要的結果?

+0

IDK的爲什麼你會想到小區** **的1222.4是1222 ... –

+0

@Antti OP只是尋找一種方式做「正確的」四捨五入。這個「ceil」例子只是一種表明「ceil」不能正確完成工作的方式。這並不意味着OP不理解爲什麼是這樣。 – poke

+0

重新打開該問題。 OP表示,他們知道,其設計「圓」不是解決方案。所以[鏈接的問題](http://stackoverflow.com/questions/18473563/python-incorrect-rounding-with-floating-point-numbers)不是真的有幫助。相反,OP似乎在問如何用小數來正確解決這個問題(以及爲什麼試圖解決方案不起作用)。 – poke

回答

5

的問題是,Decimal(1.2225)是不是你希望它是什麼:

>>> Decimal(1.2225) 
Decimal('1.2224999999999999200639422269887290894985198974609375') 

您使用的是浮動到創建小數,但浮動已經是你太不精確用例。正如你所看到的,它實際上是一個1.222499,所以它比1.2225小,因此會正確地將下調爲

爲了解決這個問題,您需要以正確的精度創建小數點,並將它們作爲字符串傳遞。然後一切按預期工作:

>>> x = Decimal('1.2225') 
>>> x.quantize(Decimal('0.001'), ROUND_HALF_UP) 
Decimal('1.223') 
>>> y = Decimal('1.2224') 
>>> y.quantize(Decimal('0.001'), ROUND_HALF_UP) 
Decimal('1.222') 
+0

啊!我沒有看到,但它非常有意義。謝謝! – user2524282

0

這是你在找什麼?

float('{:,.3f}'.format(2.2225)) 
+0

用'{:,.3f}'格式(1.2225)'(使用OP的前導輸入'1'而不是'2')比較你的格式(2.2225) 。 – poke

+0

是的。在你的答案中解釋了處理花車和四捨五入AS的問題。 –

0

這裏有三個解決方案在這個鏈接,我希望這將幫助你正是你想要做的。 https://gist.github.com/jackiekazil/6201722

from decimal import Decimal 

# First we take a float and convert it to a decimal 
x = Decimal(16.0/7) 

# Then we round it to 2 places 
output = round(x,2) 
# Output to screen 
print output 
+0

輸出= 2.29,而實際答案是「2.2857142857142856」,所以它的工作。 –

+0

雖然這是正確的,但你有點忽視OP的問題,儘管... – poke