常用类-BigInteger类和BigDecemal类
使用 BigDecimal 进行计算时,我们不能再使用算术运算符(+、-、*、/)进行算数运算,而是使用 BigDecimal 类提供的 add、subtract、multiply、divide 等方法来进行算数运算。
BigInteger: 能表示比Integer更大的数字
package com.qf.big;import java.math.BigInteger;public class Test01 {/*** 知识点:整数大数值运算类*/public static void main(String[] args) {BigInteger big1 = new BigInteger("1234567890000");BigInteger big2 = new BigInteger("1234567890000");BigInteger add = big1.add(big2);System.out.println("加法:" + add);BigInteger subtract = big1.subtract(big2);System.out.println("减法:" + subtract);BigInteger multiply = big1.multiply(big2);System.out.println("乘法:" + multiply);BigInteger divide = big1.divide(big2);System.out.println("除法:" + divide);}
}
BigDecimal:浮点数的计算
package com.qf.big;import java.math.BigDecimal;public class Test02 {/*** 知识点:小数大数值运算类*/public static void main(String[] args) {BigDecimal big1 = new BigDecimal("0.5");BigDecimal big2 = new BigDecimal("0.4");BigDecimal add = big1.add(big2);System.out.println("加法:" + add);BigDecimal subtract = big1.subtract(big2);System.out.println("减法:" + subtract);BigDecimal multiply = big1.multiply(big2);System.out.println("乘法:" + multiply);BigDecimal divide = big1.divide(big2);System.out.println("除法:" + divide);}
}
package com.qf.big;import java.math.BigDecimal;public class Test03 {/*** 知识点:小数大数值运算类*/public static void main(String[] args) {BigDecimal big1 = new BigDecimal("10");BigDecimal big2 = new BigDecimal("3");//BigDecimal 的舍入模式(RoundingMode)包含ROUND_UP、ROUND_DOWN、ROUND_CEILING、ROUND_FLOOR、ROUND_HALF_UP、ROUND_HALF_DOWN、ROUND_HALF_EVEN、ROUND_UNNECESSARYBigDecimal divide = big1.divide(big2, 3, BigDecimal.ROUND_HALF_UP);System.out.println("除法:" + divide);}
}