一 BigDecimal
解决float,double失精度问题
/*
* 构造方法:
* public BigDecimal(String val)
*
* public BigDecimal add(BigDecimal augend)
* public BigDecimal subtract(BigDecimal subtrahend)
* public BigDecimal multiply(BigDecimal multiplicand)
* public BigDecimal divide(BigDecimal divisor)
* public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode):商,几位小数,如何舍取
*/
二 代码
BIgDecimal的加,减,乘,除,和除数的规格化
import java.math.BigDecimal;
/**
* Created by hanshan on 2017/1/7 0007.
*
* float 和 double 失精度问题
*
* BigDecimal的方法
* 构造方法:
* public BigDecimal(String val)
*
* public BigDecimal add(BigDecimal augend)
* public BigDecimal subtract(BigDecimal subtrahend)
* public BigDecimal multiply(BigDecimal multiplicand)
* public BigDecimal divide(BigDecimal divisor)
* public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode):商,几位小数,如何舍取
*/
public class BigDecimalDemo {
public static void main(String[] args){
System.out.println("失精度情况");
System.out.println(0.09 + 0.01);
System.out.println(1.0 - 0.32);
System.out.println(1.015 * 100);
System.out.println(1.301 / 100);
System.out.println("\n\n\nDecimal");
BigDecimal a1=new BigDecimal("0.09");
BigDecimal b1=new BigDecimal("0.01");
System.out.println("add "+a1.add(b1));
BigDecimal a2=new BigDecimal("1.0");
BigDecimal b2=new BigDecimal("0.32");
System.out.println("sub "+a2.subtract(b2));
BigDecimal a3=new BigDecimal("1.015");
BigDecimal b3=new BigDecimal("100");
System.out.println("multiply "+a3.multiply(b3));
BigDecimal a4=new BigDecimal("1.301");
BigDecimal b4=new BigDecimal("100");
System.out.println("divide "+a4.divide(b4));
System.out.println("divide format :"+a4.divide(b4,8,BigDecimal.ROUND_HALF_UP));
// System.out.println(1.0 - 0.12);
}
}