7、数字处理工具类
BigInteger类:可以超过integer范围内的数据进行运算
构造方法:public BigInteger (String val)
常用方法:
public BigInteger add(BigIntege val) //加
public BigInteger subtract(BigIntege val) //减
public BigInteger multiply(BigIntege val) //乘
public BigInteger divide(BigIntege val) //除
public BigInteger[] divideAndRemainder (BigIntege val) //取余
public class FigureDome {
public static void main(String[] args) {
// TODO Auto-generated method stub
String val1="9823579105943";
String val2="3874564587541";
BigInteger b1=new BigInteger(val1);
BigInteger b2=new BigInteger(val2);
System.out.println(b1.add(b2));//+
System.out.println(b1.subtract(b2));// -
System.out.println(b1.multiply(b2));//*
System.out.println(b1.divide(b2));// /
System.out.println(b1.remainder(b2));//%
}
}
13698143693484
5949014518402
38062091726794425336856163
2
2074449930861
BigDecimal类:在运算的时候,float和double容易丢失精度,为了能精确的表示,计算的浮点数,java提供了BigDecimal,不可变、任意精度有符号的十进制数
构造方法:public BigDecimal(String val)
常用方法:
public BigDecimal add(BigIntege augend) //加
public BigDecimal subtract(BigIntege subrahend) //减
public BigDecimal multiply(BigIntege multipcand) //乘
public BigDecimal divide(BigIntege divide) //除
String val3="9823.579105943";
String val4="3";
BigDecimal b3=new BigDecimal(val3);
BigDecimal b4=new BigDecimal(val4);
System.out.println(b3.add(b4));//+
System.out.println(b3.subtract(b4));// -
System.out.println(b3.multiply(b4));//*
DecimalFormat::java 提供了DecimalFormat:,最快的将数字格式化为你需要的样子,例如,取两位小数
double pi=3.1415927;
System.out.println(new DecimalFormat("0").format(pi));
System.out.println(new DecimalFormat("0.00").format(pi));
System.out.println(new DecimalFormat("0.000").format(pi));//两位小数
System.out.println(new DecimalFormat("#").format(pi));//取整数部分
System.out.println(new DecimalFormat("#。##%").format(pi));//以百分号计数取两位小数:314.6%
3
3.14
3.142
3
314。%