double与float运算上的坑

本文通过两个实例展示了Java中使用Double进行乘法和除法运算时可能出现的精度问题,对比了使用BigDecimal解决这些问题的方法,强调了在金融计算等场景下使用BigDecimal的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Double乘法坑

public static void main(String[] args) {
        String a = "71.57";
        Double v = Double.parseDouble(a) * 100;
        System.out.println(v.longValue());

        BigDecimal bigDecimal = new BigDecimal(a);
        BigDecimal multiply = bigDecimal.multiply(new BigDecimal(100));
        System.out.println(multiply.longValue());
    }

运行结果 :惊不惊喜?!意不意外?!

7156
7157

二、除法喜欢加f的群众

public static void main(String[] args) {
        System.out.println("尾数0加了f:" + String.format("%.2f", 22545600L / 100.0f));
        System.out.println("尾数1加了f:" + String.format("%.2f", 22545601L / 100.0f));
        System.out.println("尾数2加了f:" + String.format("%.2f", 22545602L / 100.0f));
        System.out.println("尾数3加了f:" + String.format("%.2f", 22545603L / 100.0f));
        System.out.println("尾数4加了f:" + String.format("%.2f", 22545604L / 100.0f));
        System.out.println("尾数5加了f:" + String.format("%.2f", 22545605L / 100.0f));
        System.out.println("尾数6加了f:" + String.format("%.2f", 22545606L / 100.0f));
        System.out.println("尾数7加了f:" + String.format("%.2f", 22545607L / 100.0f));
        System.out.println("尾数8加了f:" + String.format("%.2f", 22545608L / 100.0f));
        System.out.println("尾数9加了f:" + String.format("%.2f", 22545609L / 100.0f));
        System.out.println();
        System.out.println("尾数0没加f:" + String.format("%.2f", 22545600L / 100.0));
        System.out.println("尾数1没加f:" + String.format("%.2f", 22545601L / 100.0));
        System.out.println("尾数2没加f:" + String.format("%.2f", 22545602L / 100.0));
        System.out.println("尾数3没加f:" + String.format("%.2f", 22545603L / 100.0));
        System.out.println("尾数4没加f:" + String.format("%.2f", 22545604L / 100.0));
        System.out.println("尾数5没加f:" + String.format("%.2f", 22545605L / 100.0));
        System.out.println("尾数6没加f:" + String.format("%.2f", 22545606L / 100.0));
        System.out.println("尾数7没加f:" + String.format("%.2f", 22545607L / 100.0));
        System.out.println("尾数8没加f:" + String.format("%.2f", 22545608L / 100.0));
        System.out.println("尾数9没加f:" + String.format("%.2f", 22545609L / 100.0));
    }

运行结果:开不开心?

尾数0加了f:225456.00
尾数1加了f:225456.00
尾数2加了f:225456.02
尾数3加了f:225456.05
尾数4加了f:225456.05
尾数5加了f:225456.05
尾数6加了f:225456.06
尾数7加了f:225456.08
尾数8加了f:225456.08
尾数9加了f:225456.08

尾数0没加f:225456.00
尾数1没加f:225456.01
尾数2没加f:225456.02
尾数3没加f:225456.03
尾数4没加f:225456.04
尾数5没加f:225456.05
尾数6没加f:225456.06
尾数7没加f:225456.07
尾数8没加f:225456.08
尾数9没加f:225456.09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值