BigInteger和BigDecimal

文章介绍了Java中的BigInteger用于表示任意精度整数,提供了各种数学运算,如加减乘除、模运算等;同时提到了BigDecimal用于高精度十进制运算,适合商业计算需求。示例展示了如何使用这两个类进行基本操作。
摘要由CSDN通过智能技术生成

1 BigInteger

  • Integer类作为int的包装类,能储存的最大整数值为231-1,Long类也是有限的,最大为263-1。如果要表示再大的整数,不管是基本数据类型还是他们的包装类都无能为力,不用说进行运算了。
  • java.math包的BigInteger可以表示不可变的任意精度的整数。BigInteger 提供所有 Java 的基本整数操作符的对应物,并提供java.lang.Math 的所有相关方法。另外, BigInteger 还提供以下运算:模算术、 GCD 计算、质数测试、素数生成、位操作以及一些其他操作。
  • 构造器 BigInteger(String val): 根据字符串构建BigInteger对象
  • 常用方法
    • public BigInteger abs():返回此 BigInteger 的绝对值的 BigInteger。
    • BigInteger add(BigInteger val) :返回其值为 (this + val) 的 BigInteger
    • BigInteger subtract(BigInteger val) :返回其值为 (this - val) 的 BigInteger
    • BigInteger multiply(BigInteger val) :返回其值为 (this * val) 的 BigInteger
    • BigInteger divide(BigInteger val) :返回其值为 (this / val) 的 BigInteger。整数相除只保留整数部分。
    • BigInteger remainder(BigInteger val) :返回其值为 (this % val) 的 BigInteger。
    • BigInteger[] divideAndRemainder(BigInteger val):返回包含 (this / val) 后跟(this % val) 的两个 BigInteger 的数组。
    • BigInteger pow(int exponent) :返回其值为 (thisexponent) 的 BigInteger。

2 BigDecimal

  • 一般的Float类和Double类可以用来做科学计算或工程计算,但在商业计算中,要求数字精度比较高,故用到java.math.BigDecimal类。
  • BigDecimal类支持不可变的、任意精度的有符号十进制定点数。
  • 构造器
    • public BigDecinal(double val)
    • public BigDecimal(String val)
  • 常用方法
    • public BigDecimal add(BigDecimal augend)
    • public BigDecimal subtract(BigDecimal subtrahend)
    • public BigDecimal multiply(BigDecimal multiplicand)
    • public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
public class BigIntegerDemo {

    @Test
    public void test1() {
        System.out.println(Integer.MAX_VALUE);

        Integer i1 = 2147483647;

//        Integer i2 = 2147483648;

        BigInteger i3= new BigInteger("10");
        System.out.println(i3);

        BigInteger i4 = new BigInteger("15");



        BigInteger i5 = i3.add(i4);
        System.out.println(i5);

        BigInteger[] arrs = i3.divideAndRemainder(new BigInteger("3"));

        System.out.println(Arrays.toString(arrs));

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值