Double计算精度丢失(金融入门知识点)

Double计算精度丢失(金融入门知识点)

最近工作发现不少同事对于double精度丢失还不了解,对于一些新手java程序员,这倒是还可以理解,但是如果是已经工作了几年的老鸟,还不清楚,那就要抓紧补课了。废话不多说,进入今天的正题。

一.double精度丢失

public 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.错误用法一

例如:

public static void main(String[] args) {
    double a = 0.1;
    System.out.println(new BigDecimal(a));
}

会打印出:0.1000000000000000055511151231257827021181583404541015625

官方给出的注释如下:

The 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.错误用法二
public static void main(String[] args) {
    double a = 0.55555555555555555;
    System.out.println(BigDecimal.valueOf(a));
}

打印的结果为:0.5555555555555556,这是由于double存在一定的精度,会进行四舍五入,因此在转换为BigDecimal的时候就会我们预想的不一致。

四.BigDecimal正确的用法

注意:通过阅读注释,以下用法也是官方推荐的用法。

public 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));
}

打印结果为:

0.55555555555555555
9.9

官方注释如下:

The {@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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值