java常用类库之大数字操作类

BigInteger

BigInteger包含了大整数类的加减乘除操作,这里特别说明保留余数的除法操作

public BigInteger[ ] divideAndRemainder(BigInteger val)返回的数组第一个值为商,第二个为余数

public class BigIntegerDemo {
	public static void main(String[] args) {
		String num1 = "1111111111111111";
		String num2 = "33333333333333333333333";
		BigInteger big1 = new BigInteger(num1); // 实例化BigInteger对象
		BigInteger big2 = new BigInteger(num2); // 实例化BigInteger对象
		System.out.println("加法操作:" + big1.add(big2));
		System.out.println("减法操作:" + big1.subtract(big2));
		System.out.println("乘法操作:" + big1.multiply(big2));
		System.out.println("除法操作:" + big1.divide(big2));
		BigInteger result[] = big1.divideAndRemainder(big2);// 进行触发操作,有余数
		System.out.println("相除之后的商是:" + result[0]);
		System.out.println("相除之后的余数是:" + result[1]);
	}

}

BigDecimal

public static final int ROUND_HALF_UP 常量  表示向上进位

public BigDecimal dvide(BigDecimal divisor,int scale,int roundingMode)  除法操作  参数分别是(除数、保留小数位数、进位模式)

class MyMath {
	public static double add(String num1, String num2) {
		BigDecimal bd1 = new BigDecimal(num1);
		BigDecimal bd2 = new BigDecimal(num2);
		return bd1.add(bd2).doubleValue();
	}

	public static double sub(String num1, String num2) {
		BigDecimal bd1 = new BigDecimal(num1);
		BigDecimal bd2 = new BigDecimal(num2);
		return bd1.subtract(bd2).doubleValue();
	}

	public static double mul(String num1, String num2) {
		BigDecimal bd1 = new BigDecimal(num1);
		BigDecimal bd2 = new BigDecimal(num2);
		return bd1.multiply(bd2).doubleValue();
	}

	public static double div(String num1, String num2, int scale) {
		BigDecimal bd1 = new BigDecimal(num1);
		BigDecimal bd2 = new BigDecimal(num2);
		return bd1.divide(bd2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	public static double round(double num, int scale) {
		BigDecimal bd1 = new BigDecimal(num);
		BigDecimal bd2 = new BigDecimal(1);
		return bd1.divide(bd2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}
}

public class BigDecimalDemo {
	public static void main(String[] args) {
		String num1 = "12345.07891";
		String num2 = "3333.5101";
		System.out.println("加法操作:" + MyMath.round(MyMath.add(num1, num2), 2));
		System.out.println("减法操作:" + MyMath.round(MyMath.sub(num1, num2), 2));
		System.out.println("乘法操作:" + MyMath.round(MyMath.mul(num1, num2), 2));
		System.out.println("除法操作:" + (MyMath.div(num1, num2, 2)));
	}
}


你可能感兴趣的:(BigDecimal,BIgInteger,大数字操作)