Java中的大数值使用

在Java中,偶尔会遇到超大数值,超出了已有的int,double,float等等你已知的整数、浮点数范围,那么可以使用java.math包中的两个类:BigInteger和BigDecimal。

这两个类很牛批!!可以处理包含任意长度的数值。BigInteger类实现了任意精度的整数运算,BigDecimal实现了任意精度的浮点数运算。

类不可以直接被使用,那么就需要调用它们的下属方法来使用,其中静态的valueOf方法可以将普通数值转化为大数值:

BigInteger a =  BigInteger.valueOf (100) ;

但是万事做不到完美,使用了大数值,加减乘除等基本运算就发生了改变,不再是平常的运算符(如:+和*),而是有了固定的方法需要去调用。

下面举两个例子,分别是加和乘(add 和 multiply):

BigInteger c = a.add(b); //c=a+b

BigInteger d = c.multiply(b.add(BigInteger.valueOf (2))); //d=c*(b+2)

下面列举BigInteger类和BigDecimal类中的方法

java.math.BigInteger1.1

扫描二维码关注公众号,回复: 2294813 查看本文章
  • 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,返回负数;否则,返回正数。

  • static BigInteger valueOf (long x)

返回值等于x的大整数。

java.math.BigDecimal1.1

  • BigDecimal add(BigDecimal other)
  • BigDecimal subtract(BigDecimal other)
  • BigDecimal multiply(BigDecimal other)
  • BigDecimal divide(BigDecimal other RoundingMode mode) 5.0

返回这个大实数和另一个大实数other的和、差、积、商。想要计算商,必须给出舍入方式(rounding mode)。RoundingMode.HALF_UP是最常见的四舍五入方式。它适用于常规的计算。有关其它的舍入方式请参看API文档——见文低附录。

  • int compareTo(BigDecimal other)

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

  • static BigDecimal valueOf (long x)
  • static BigDecimal valueOf (long x , int scale)

返回值为x或x / 10scale 的一个大实数

附录:API文档——https://pan.baidu.com/s/14IZu6fJH4uB8rnsfSACz4w

猜你喜欢

转载自www.cnblogs.com/dalingxuan/p/9348533.html