Java:为什么在现实世界中我们应该使用 BigDecimal 而不是 Double?

Java:Why should we use BigDecimal instead of Double in the real world?(Java:为什么在现实世界中我们应该使用 BigDecimal 而不是 Double?)
本文介绍了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".

你能解释一下这个问题吗?

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)