记一次parseDouble转换字符串为Double格式,遇到3出错问题,double乘以整数导致精度丢失问题

public class Test {
    public static void main(String[] args) {
        String s = "0.0002000000";
        Double aDouble = Double.parseDouble(s);
        Double bDouble = Double.parseDouble(s)*10000;
        System.out.println("aDouble = " + aDouble);
        System.out.println("bDouble = " + bDouble);
    }
}

1ab42b3876cb40d6b078edf481d774a7.png

public class Test {
    public static void main(String[] args) {
        String s = "0.0003000000";
        Double aDouble = Double.parseDouble(s);
        Double bDouble = Double.parseDouble(s)*10000;
        System.out.println("aDouble = " + aDouble);
        System.out.println("bDouble = " + bDouble);
    }
}

dd3b5f17530c4e3c9b4f66b46936d96f.png

public class Test {
    public static void main(String[] args) {
        String s = "0.0005000000";
        Double aDouble = Double.parseDouble(s);
        Double bDouble = Double.parseDouble(s)*10000;
        System.out.println("aDouble = " + aDouble);
        System.out.println("bDouble = " + bDouble);
    }
}

fdc2afd746fd469aaa4c37138eaaad13.png

 原因分析:double乘以整数,导致精度丢失

测试使用BigDecimal的multiply

public class Test {
    public static void main(String[] args) {
        String s = "0.0003000000";
        BigDecimal bigDecimal = new BigDecimal(s);
        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(10000));
        int i = bigDecimal.multiply(bigDecimal1).intValue();
        BigDecimal multiply = bigDecimal.multiply(bigDecimal1);
        System.out.println("i = " + i);
        System.out.println("multiply = " + multiply);
    }
}

9dadf7bec10f4d3cb3b154739cbc3298.png

 涉及金融数据等大数据加减乘除等,还是建议使用BigDecimal的API

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值