JAVA中BigDecimal数据
一点说明:float和double类型的主要设计目标是为了科学计算和工程计算。他们执行二进制浮点运算,这是为了在广域数值范围上提供
较为精确的快速近似计算而精心设计的。然而,它们没有提供完全精确的结果,所以不应该被用于要求精确结果的场合。但是,货币计算往往要求结果精确,这时候可以使用int、long或BigDecimal。
用
解决的两个问题,BigDecimal类型数字比较(大小精度)
-1,BigDecimal类型数据比较方法
-2,BIgDecimal中数据格式的控制(格式化类型,以及保留类型)
-3,BigDecimal是不可变类
第一个问题:比较的时候一般用:compareTo
BigDecimal a=new BigDecimal("2.00");
BigDecimal b=new BigDecimal("2.0");
a.compareTo(b)=0;//比较精度和大小 true
a.equals(b)=0;//不比较精度 false
/**
加一点,在使用过程中对Bigdecimal另外i行数据判空的时候直接使用==null即可
**/
第二个问题:
适用情况:有多位小数保留其中的某几位
BigDecimal a=new BigDecimal(2.888);
a.setScale(2,RoundingMode.HALF_UP);//后面参数是四舍五入,也有其他模式的
// 2.89
格式控制:
DecimalFormat df1 = new DecimalFormat("####.000");
System.out.println(df1.format(1234.56)); //1234.560
BigDecimal是不可变类:每一个操作(加减乘除等)都会返回一个新的对象
BigDecimal a =new BigDecimal("1.22");
System.out.println("construct with a String value: " + a);//a=1.22
BigDecimal b =new BigDecimal("2.22");
a.add(b);
System.out.println("a plus b is : " + a);//a=1.22不是3.44
追加一些Integer和int的知识:
由于Integer变量实际上是对一个Integer对象的引用,所以两个通过new生成的Integer变量永远是不相等的(因为new生成的是两个对象,其内存地址不同)。
Integer i = new Integer(100);
Integer j = new Integer(100);
System.out.print(i == j); //false
System.out.print(i.equals(i));//true
Integer变量和int变量比较时,只要两个变量的值是向等的,则结果为true(因为包装类Integer和基本数据类型int比较时,java会自动拆包装为int,然后进行比较,实际上就变为两个int变量的比较
Integer i = new Integer(100);
int j = 100;
System.out.print(i == j); //true
非new生成的Integer变量和new Integer()生成的变量比较时,结果为false。(因为 ①当变量值在-128~127之间时,非new生成的Integer变量指向的是java常量池中的对象,而new Integer()生成的变量指向堆中新建的对象,两者在内存中的地址不同;②当变量值在-128~127之间时,非new生成Integer变量时,java API中最终会按照new Integer(i)进行处理(参考下面第4条),最终两个Interger的地址同样是不相同的)
Integer i = new Integer(100);
Integer j = 100;
System.out.print(i == j); //false
对于两个非new生成的Integer对象,进行比较时,如果两个变量的值在区间-128到127之间,则比较结果为true,如果两个变量的值不在此区间,则比较结果为false
Integer i = 100;
Integer j = 100;
System.out.print(i == j); //true
Integer i = 128;
Integer j = 128;
System.out.print(i == j); //false