在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

  • 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

最新文章

  1. Sql Cursor example
  2. android常见问题(一)
  3. No.014 Longest Common Prefix
  4. jetty使用教程(嵌入eclipse开发)
  5. 【转】bShare分享插件的使用
  6. ubuntu虚拟机安装
  7. 【Todo】Kerberos、OpenSSL、OAuth2.0等一系列验证权限安全相关学习
  8. Atom编辑器入门到精通(三) 文本编辑基础
  9. android学习之BUG——The connection to adb is down, and a severe error has occured.
  10. Java 单元测试Junit
  11. 第33篇 js 常用简单的写法
  12. MyEclipse弹出提示窗口
  13. windows socket 文件下载上传
  14. numpy 多维数组及数组操作
  15. Html5游戏框架createJS组件--EaselJS
  16. linux网络操作 配置文件
  17. [转]springcloud(九):配置中心和消息总线(配置中心终结版)
  18. ORA-16038: log 3 sequence# 103 cannot be archived
  19. airway之workflow
  20. 26_多线程_第26天(Thread、线程创建、线程池)_讲义

热门文章

  1. java基础——并发1
  2. CCNA-Part1:网络基础概念
  3. java后台框架面试必须会的东西
  4. vue环境配置脚手架搭建,生命周期,钩子
  5. The main method caused an error: java.util.concurrent.ExecutionException: org.apache.flink.runtime.client.JobSubmissionException: Failed to submit JobGraph.
  6. 手摸手带你理解Vue的Watch原理
  7. sql:主键(primary key)和唯一索引(unique index)区别
  8. For setting NODE_ENV you can use any of these methods.
  9. 泊车SLAM文献整理
  10. 一个ioc例子jdk和spring版本导致问题