JAVA常用API:大数据运算BigInteger类和BigDecimal类

JAVA中long型为最大整数类型,对于超大型的数据如何去表示呢,在JAVA世界中,超过long型的整数已经不能被称之为基本数据类型了,它们被封装成BigInteger对象,在BigInteger类中,实现四则运算都是通过方法来实现的,而不是采用运算符号来实现。

一、BigInteger类的构造方法

1.传入byte数组,创建BigInteger对象

BigInteger bi = new BigInteger(byte[] bytes);

2. 传入字符串,创建BigInteger对象,这种方式比较多采用,因为String的长度足可以容纳任何长度的数字

BigInteger bi = new BigInteger("12531534534313413545346");

3. 将指定进制的字符串,转换为BigInteger对象

BigInteger bi = new BigInteger("1101",2); 表示传入字符串为二进制,转换为十字制后创建BigInteger对象

二、BigInteger类的四则运算

1. 加法运算, BigInteger b3 = b1.add(BigInteger b2);

b1.add(b2);

2. 减法运算,b1.subtract(b2); 返回值为BigInteger对象

3.乘法运算:b1.multiply(b2);返回值为BigInteger对象

4.除法运算:b1.divide(b2);

三、BigDecimal 类

System.out.println(0.09+0.01); //0.09999999999999999

System.out.println(1.0-0.32); //0.6799999999999999

System.out.println(1.015*100); //101.49999999999999

System.out.println(1.301/100); //0.013009999999999999

double和float类型在运算中很容易失去精度,造成数据的不准确,JAVA提供了BigDecimal类可以实现浮点数据的高精度运算。

四、BigDecimal的构造方法

1. BigDecimal(BigInteger val);将BigInteger对象转换成BigDecimal对象

2. BigDecimal(String str); 将字符串表示的数字,转成BigInteger对象

五、BigDecimal四则运算

1. 加减乘都和BigInteger一样

除法运算,因为可能出现无限不循环小数,会导致数学异常MathmeticException,所以进行除法运算时,应指定保留的小数位和舍入模式

BigDecimal d1 = new BigDecimal("1.301");

BigDecimal d2 = new BigDecimal("100");

BigDecimal d3 = d1.divide(d2,2,);

divide(BigDecimal divisor, int scale, RoundingMode roundingMode)

BigDecimal divisor:表示除数

int scale:表示保留几位小数

roundingMode:表示舍入的模式

ROUND_UP: 始终往上+1

ROUND_DOWN:始终舍弃

ROUND_HALF_UP:四舍五入

 

posted on 2018-06-12 16:52  adamal  阅读(195)  评论(0)    收藏  举报