Java:为什么要在现实世界中使用BigDecimal而不是Double? [英] Java:Why should we use BigDecimal instead of Double in the real world?

查看:455
本文介绍了Java:为什么要在现实世界中使用BigDecimal而不是Double?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理真实世界的货币价值时,我建议使用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".

你能否提出这个问题?

推荐答案

这是被称为精度损失,在工作时非常明显具有非常大的数字或非常小的数字。使用小数的十进制数的二进制表示在许多情况下是近似值而不是绝对值。了解为什么你需要读取浮点数表示的二进制。以下是一个链接: http://en.wikipedia.org/wiki/IEEE_754-2008。这是一个快速演示:

在bc(任意精度计算器语言),精度= 10:

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/30)= 0.6083333332

(1/3 + 1/12 + 1/8)= 0.541666666666666

(1/3 + 1 / 12)= 0.416666666666666

(1/3+1/12+1/8+1/30) = 0.6083333332
(1/3+1/12+1/8) = 0.541666666666666
(1/3+1/12) = 0.416666666666666

Java double:

0.6083333333333333

0.5416666666666666

0.41666666666666663 < br>

Java double:
0.6083333333333333
0.5416666666666666
0.41666666666666663

Java float:

Java float:

0.60833335

0.5416667

0.4166667

0.60833335
0.5416667
0.4166667



如果您是银行,并且每天负责数千笔交易,即使它们不是来自一个和同一个帐户(或者也许他们),你必须有可靠的数字。二进制浮标是不可靠的 - 除非您了解它们的工作原理及其局限性。


If you are a bank and are responsible for thousands of transactions every day, even though they are not to and from one and same account (or maybe they are) you have to have reliable numbers. Binary floats are not reliable - not unless you understand how they work and their limitations.

这篇关于Java:为什么要在现实世界中使用BigDecimal而不是Double?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆