BigInteger和BigDecimal类

BigInteger和BigDecimal类

此系列笔记来源于

BiliBili韩顺平老师的Java基础课


介绍:

BigInteger适合保存比较大的整型

BigDecimal适合保存精度更高的浮点型

BigInteger

BigInteger运算时需要用对应的方法,不能直接 + - * /

BigInteger a = new BigInteger("123");
BigInteger b = new BigInteger("321");

BigInteger add = a.add(b);
BigInteger subtract = a.subtract(b);
BigInteger multiply = a.multiply(b);
BigInteger divide = a.divide(b);

BigDecimal

BigDecimal运算时需要用对应的方法,不能直接+-*/

BigDecimal a = new BigDecimal("1.1111");
BigDecimal b = new BigDecimal("2.1111");

BigDecimal add = a.add(b);
BigDecimal subtract = a.subtract(b);
BigDecimal multiply = a.multiply(b);    
BigDecimal divide = a.divide(b);//可能抛出异常ArithmeticException(无限循环小数,除数为)
//调用divide方法时,指定精度即可 BigDecimal.ROUND_CEILING,若有无限循环小数会保留分子的精度
BigDecimal divide = a.divide(b, BigDecimal.ROUND_CEILING); 
posted @ 2022-04-11 12:51  Yra  阅读(28)  评论(0)    收藏  举报