【Java】BigDecimal

public class BigDecimalUtil {

    private BigDecimalUtil(){

    }


    public static BigDecimal add(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2);
    }

    public static BigDecimal sub(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2);
    }


    public static BigDecimal mul(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2);
    }

    public static BigDecimal div(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        //除不尽的情况
        return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);//保留2位小数,四舍五入
    }

}

Test

public class BigDecimalTest {

    @Test
    public void test1(){
        System.out.println(0.05+0.01);
        System.out.println(1.0-0.42);
        System.out.println(4.015*100);
        System.out.println(123.3/100);
        //可能导致大型故障
        //0.060000000000000005
        //0.5800000000000001
        //401.49999999999994
        //1.2329999999999999

        //实际数据库存float、double什么的 我们来封装一个BigDecimalUtil工具类 转换
        System.out.println(BigDecimalUtil.add(0.05,0.01));
        System.out.println(BigDecimalUtil.sub(1.0,0.42));
        System.out.println(BigDecimalUtil.mul(4.015,100));
        System.out.println(BigDecimalUtil.div(123.3,100));
        //0.06
        //0.58
        //401.5000
        //1.23
    }







    @Test
    public void test2(){
        BigDecimal b1 = new BigDecimal(0.05);
        BigDecimal b2 = new BigDecimal(0.01);
        System.out.println(b1.add(b2));
        //0.06000000000000000298372437868010820238851010799407958984375
    }

    @Test
    public void test3(){
        //商业计算  一定要用BigDecimal的String构造器
        BigDecimal b1 = new BigDecimal("0.05");
        BigDecimal b2 = new BigDecimal("0.01");
        System.out.println(b1.add(b2));
        //0.06   string
    }
   

}

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值