BigInteger、BigDecimal

在高精度的计算中使用的两个类,BigInteger和BigDecimal分别表示任意精度的整数与浮点数

import java.math.BigInteger;

/**
 * 不可变的任意精度的整数
 */
public class BigIntegerDemo {

    public static void main(String args[]) {
        /**
         * 使用比特数组
         */
        BigInteger bigInteger1 = new BigInteger(new byte[]{1, 1, 1, 1, 1, 1});

        /**
         * 使用字符串构建该字符串
         */
        BigInteger bigInteger2 = new BigInteger("987654321");

        /**
         * 使用字符串构建十进制的BigInteger
         */
        BigInteger bigInteger3 = new BigInteger("98765", 10);


        /**
         * 把长整形的数字转换成BigInteger
         */
        BigInteger bigInteger4 = BigInteger.valueOf(1234567L);

        System.out.println("BigInteger的整形值==" + bigInteger1.intValue());

        System.out.println("BigInteger的绝对值==" + bigInteger1.abs());

        System.out.println("两个bigInteger相加==" + bigInteger1.add(bigInteger2));

        System.out.println("两个bigInteger相除==" + bigInteger3.divide(new BigInteger("98765")));

        /**
         * 如果此 BigInteger 可能为素数,则返回 true,如果它一定为合数,则返回 false。如果 certainty <= 0,则返回 true
         */
        System.out.println("判断该数字是素数还是合数==" + bigInteger4.isProbablePrime(-1));
    }
}

运行结果:
BigInteger的整形值==16843009
BigInteger的绝对值==1103823438081
两个bigInteger相加==1104811092402
两个bigInteger相除==1
判断该数字是素数还是合数==true

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

/**
 * 不可变的、任意精度的有符号十进制数
 * 与之相关的还有两个类:
 * java.math.MathContext:
 * 该对象是封装上下文设置的不可变对象,它描述数字运算符的某些规则,如数据的精度,舍入方式等。
 * java.math.RoundingMode:这是一种枚举类型,定义了很多常用的数据舍入方式。
 */
public class BigDecimalDemo {

    public static void main(String args[]) {
        /**
         *使用char[]数组来构建BigDecimal
         */
        BigDecimal bigDecimal1 = new BigDecimal("987654321.876543".toCharArray(), 0, "987654321.876543".toCharArray().length);


        /**
         * 使用字符串构建
         */
        BigDecimal bigDecimal2 = new BigDecimal("0.98766554456");


        /**
         *  使用字符串创建BigDecimal,3是有效数字个数
         */
        BigDecimal bigDecimal3 = new BigDecimal("9876.654332", new MathContext(3, RoundingMode.UP));


        System.out.println("两个数字相加==" + bigDecimal1.add(bigDecimal2));

        System.out.println("两个数字相加==" + bigDecimal1.add(bigDecimal2, new MathContext(3, RoundingMode.UP)));
        System.out.println("两个数字相减==" + bigDecimal1.subtract(bigDecimal3).toPlainString());
    }
}

运行结果:
两个数字相加==987654322.86420854456
两个数字相加==9.88E+8
两个数字相减==987644441.876543


你可能感兴趣的:(BigInteger、BigDecimal)