- Double计算精度丢失(金融入门知识点)
- 一.double精度丢失
- 二.为什么double会精度丢失
- 三.BigDecimal错误的用法
- 四.BigDecimal正确的用法
Double计算精度丢失(金融入门知识点)
最近工作发现不少同事对于double精度丢失还不了解,对于一些新手java程序员,这倒是还可以理解,但是如果是已经工作了几年的老鸟,还不清楚,那就要抓紧补课了。废话不多说,进入今天的正题。
一.double精度丢失
1
2
3
4
5
6public static void main(String[] args) { double a = 3; double b = 3.3; System.out.println(a * b); }
执行以上java代码,期望打印9.9,但是实际返回的是:9.899999999999999
二.为什么double会精度丢失
这是由于double不是精确计算,存在精度丢失。至于为什么会精度丢失,是由于计算机在进行计算的时候是采用二进制,需要将10进制转换成二进制,但是很多10进制数无法使用二进制来精确表示。
例如:0.1,它对应的二进制0.0001100110011…无限循环,只能无限逼近0.1,这就导致了精度丢失的问题。
想深入了解可以看 这篇文章,讲的不错。
三.BigDecimal错误的用法
可以使用 BigDecimal 类来进行精确计算,可以避免精度丢失的问题。
但是在使用 BigDecimal 也存在很多坑。
- 1.错误用法一
例如:
1
2
3
4
5public static void main(String[] args) { double a = 0.1; System.out.println(new BigDecimal(a)); }
会打印出:0.1000000000000000055511151231257827021181583404541015625
官方给出的注释如下:
1
2
3
4
5
6
7
8
9The results of this constructor can be somewhat unpredictable. One might assume that writing {@code new BigDecimal(0.1)} in Java creates a {@code BigDecimal} which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a {@code double}
这是由于0.1无法精确的表示为一个二进制数导致的。
- 2.错误用法二
1
2
3
4
5public static void main(String[] args) { double a = 0.55555555555555555; System.out.println(BigDecimal.valueOf(a)); }
打印的结果为:0.5555555555555556,这是由于double存在一定的精度,会进行四舍五入,因此在转换为BigDecimal的时候就会我们预想的不一致。
四.BigDecimal正确的用法
注意:通过阅读注释,以下用法也是官方推荐的用法。
1
2
3
4
5
6
7
8
9public static void main(String[] args) { String a = "0.55555555555555555"; System.out.println(new BigDecimal(a)); BigDecimal b = new BigDecimal("3"); BigDecimal c = new BigDecimal("3.3"); System.out.println(b.multiply(c)); }
打印结果为:
1
2
30.55555555555555555 9.9
官方注释如下:
1
2
3
4
5
6
7The {@code String} constructor, on the other hand, is perfectly predictable: writing {@code new BigDecimal("0.1")} creates a {@code BigDecimal} which is <i>exactly</i> equal to 0.1, as one would expect. Therefore, it is generally recommended that the {@linkplain #BigDecimal(String) <tt>String</tt> constructor} be used in preference to this one.
引用:
1.https://www.cnblogs.com/backwords/p/9826773.html
2.https://blog.csdn.net/linghuainian/article/details/90270462
最后
以上就是虚幻绿草最近收集整理的关于Double计算精度丢失(金融入门知识点)Double计算精度丢失(金融入门知识点)的全部内容,更多相关Double计算精度丢失(金融入门知识点)Double计算精度丢失(金融入门知识点)内容请搜索靠谱客的其他文章。
发表评论 取消回复