Java中大数值是什么?数值想存多大存多大

如果我们常用的整数和浮点数不能满足需求时,java.math包中有两个很有用的类:BigInteger 和 BigDecimal 。这两个类可以处理任意长度数字序列的数值,就是说有了这两个类,想存多大数就能存多大。

但是我们不能用平常用的算数运算符(+或者*等)来处理大数值,而是需要它专用的方法,需要注意的是大数值不能直接跟普通数值计算,我们可以使用 valueOf 方法将普通数值转换为大数值,具体请看下面代码理解:

这段代码用BigInteger类进行演示,BigDecimal类使用方法相同,不过就是BigInteger类实现了任意精度的整数运算,BigDecimal实现了任意精度的的浮点数运算。

import java.math.BigInteger;

public class Test {
    
    


    public static void main(String[] args) {
    
    
        //实例化一个BigInteger 类型 对象 传入初始值
        BigInteger a = new BigInteger("999999999999999999999999999999");
        System.out.println("大数值a的值为" + a);
        //用BigInteger.valueOf()将33 转换为 大数值
        BigInteger b = BigInteger.valueOf(33);
        // 可以理解为 c = a + b
        BigInteger c = a.add(b);
        System.out.println("大数值c的值为:" + c);
        //可以理解为 d = c * (b + 2)
        BigInteger d = c.multiply(b.add(BigInteger.valueOf(2)));
        System.out.println("大数值d为" + d);
    }

    }

运行结果如下:
在这里插入图片描述
下面是BigInteger 类下的 常用 方法:

BigInteger add(BigInteger other)
实现两个大整数相加

BigInteger subtract(BigInteger other)
实现两个大整数相减

BigInteger multiply(BigInteger other)
实现两个大整数相乘

BigInteger divide(BigInteger other)
实现两个大整数相除

BigInteger mod(BigInteger other)
返回这个大整数与另一个大整数other的和、差、积、商以及余数

int compareTo(BigInteger other)
如果这个大整数与另一个大整数other相等,返回0;如果这个大整数小于另一个大整数other,返回负数;否则,返回正数 。

下面是BigDecimal类下的 常用 方法:
BigDecimal add(BigDecimal other)
实现两个大实数相加

BigDecimal subtract(BigDecimal other)
实现两个大实数相减

BigDecimal multiply(BigDecimal other)
实现两个大实数相乘

BigDecimal divide(BigDecimal other RoundingMode mode) 5.0
返回这个大实数与另一个大实数other的和、差、积、商。想要计算商,必须给出舍入方式(rounding mode)。RoundMode.HALF_UP是在学校中学习的四舍五入方式(即,数值0到4舍去,数值5到9进位)。

int compareTo(BigDecimal other)
如果这个大整数与另一个大实数other相等,返回0;如果这个大实数小于另一个大实数other,返回负数;否则,返回正数 。

都看到这里了就拜托点个赞吧,非常感谢。
菜鸟总结,如有错误请指正下。

猜你喜欢

转载自blog.csdn.net/qq_46209845/article/details/113153363