Java(六)——常用类 --- 大数运算
基本数据类型long ,double 都是有取值范围.遇到超过范围数据怎么办.引入了大数运算对象. 超过取出范围了,不能称为数字了,称为对象
java.math包 : BigInteger大整数, BigDecimal大浮点(高精度,不损失精度)
-
BigInteger类使用,计算超大整数的
-
构造方法直接new BigInteger(String str) 数字格式的字符串,长度任意
-
BigInteger add(BigInteger b)计算两个BigInteger的数据求和
-
BigInteger subtract(BigInteger b)计算两个BigInteger的数据求差
-
BigInteger multiply(BigInteger b)计算两个BigInteger的数据求乘积
-
BigInteger divide(BigInteger b)计算两个BigInteger的数据求商
-
public static void main(String[] args) {
//创建大数据运算对象
BigInteger b1 = new BigInteger("2345673456786554678996546754434343244568435678986");
BigInteger b2 = new BigInteger("8765432345678987654323456787654");
//b1+b2 求和
BigInteger add = b1.add(b2);
System.out.println("add = " + add);
//b1 - b2 求差
BigInteger subtract = b1.subtract(b2);
System.out.println("subtract = " + subtract);
//b1 * b2 求积
BigInteger multiply = b1.multiply(b2);
System.out.println("multiply = " + multiply);
//b1 / b2 求商
BigInteger divide = b1.divide(b2);
System.out.println("divide = " + divide);
}
-
BigDecimal 类使用,计算超大浮点数
-
构造方法,和BigInteger一样
-
方法 + - * 和BigInteger一样
-
BigDecimal divide除法运算
-
divide(BigDecimal big,int scalar,int round)方法有三个参数
-
big 被除数
-
scalar 保留几位
-
round 保留方式
-
-
保留方式 : 该类的静态成员变量
-
BigDecimal.ROUND_UP 向上+1
-
BigDecimal.ROUND_DOWN 直接舍去
-
BigDecimal.ROUND_HALF_UP 四舍五入
-
-
public static void main(String[] args) {
BigDecimal b1 = new BigDecimal("3.55");
BigDecimal b2 = new BigDecimal("2.12");
/* System.out.println(b1.add(b2));
System.out.println(b1.subtract(b2));
System.out.println(b1.multiply(b2));*/
//b1 / b2
/**
* 1.674528301886792
* 除不尽,出现异常
* 高精度运算,不能产生无序循环小数,无限不循环
* 保留几位,怎么保留
*
* BigDecimal.ROUND_UP 向上+1
* BigDecimal.ROUND_DOWN 直接舍去
* BigDecimal.ROUND_HALF_UP 四舍五入
*/
BigDecimal divide = b1.divide(b2,3,BigDecimal.ROUND_HALF_UP);
System.out.println("divide = " + divide);
}