問題描述
在處理現實世界的貨幣值時,建議我使用 BigDecimal 而不是 Double.但我沒有得到令人信服的解釋,除了通常這樣做".
When dealing with real world monetary values, I am advised to use BigDecimal instead of Double.But I have not got a convincing explanation except, "It is normally done that way".
你能解釋一下這個問題嗎?
Can you please throw light on this question?
推薦答案
這稱為精度損失,在處理非常大或非常小的數字時非常明顯.帶基數的十進制數的二進制表示在許多情況下是近似值而不是絕對值.要了解為什么您需要閱讀二進制中的浮點數表示.這是一個鏈接:http://en.wikipedia.org/wiki/IEEE_754-2008一個>.這是一個快速演示:
在精度=10 的 bc(任意精度計算器語言)中:
It's called loss of precision and is very noticeable when working with either very big numbers or very small numbers. The binary representation of decimal numbers with a radix is in many cases an approximation and not an absolute value. To understand why you need to read up on floating number representation in binary. Here is a link: http://en.wikipedia.org/wiki/IEEE_754-2008. Here is a quick demonstration:
in bc (An arbitrary precision calculator language) with precision=10:
(1/3+1/12+1/8+1/15) = 0.6083333332
(1/3+1/12+1/8) = 0.541666666666666
(1/3+1/12) = 0.416666666666666
(1/3+1/12+1/8+1/15) = 0.6083333332
(1/3+1/12+1/8) = 0.541666666666666
(1/3+1/12) = 0.416666666666666
Java 雙重:
0.6083333333333333
0.5416666666666666
0.41666666666666663
Java double:
0.6083333333333333
0.5416666666666666
0.41666666666666663
Java 浮點數:
Java float:
0.60833335
0.5416667
0.4166667
0.60833335
0.5416667
0.4166667
這篇關于Java:為什么在現實世界中我們應該使用 BigDecimal 而不是 Double?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!