BigDecimal加減乘除,比較
阿新 • • 發佈:2018-12-11
BigDecimal通過compareTo方法來進行比較.
返回的結果是int型別,-1表示小於,0是等於,1是大於.
java.math.BigDecimal。
BigDecimal一共有4個夠造方法:
public static double add(double v1,double v2) --- 加
public static double sub(double v1,double v2) --- 減
public static double mul(double v1,double v2) --- 乘
public static double div(double v1,double v2) --- 除
//加法--引數為:String,String 四捨五入保留num位小數 public BigDecimal add(String num1, String num2, int num) { BigDecimal result = new BigDecimal(num1).add(new BigDecimal(num2)).setScale(num, BigDecimal.ROUND_HALF_UP); result = result.compareTo(new BigDecimal("0E-8")) == 0 ? new BigDecimal("0") : result; return result; } //加法--引數為:Double,Double 四捨五入保留num位小數 public static BigDecimal add(Double num1, Double num2, int num) { BigDecimal result = BigDecimal.valueOf(num1).add(BigDecimal.valueOf(num2)).setScale(num, BigDecimal.ROUND_HALF_UP); result = result.compareTo(new BigDecimal("0E-8")) == 0 ? new BigDecimal("0") : result; return result; } //減法--引數為:String,String 四捨五入保留num位小數 public static BigDecimal subtract(String num1, String num2, int num) { BigDecimal result = new BigDecimal(num1).subtract(new BigDecimal(num2)).setScale(num, BigDecimal.ROUND_HALF_UP); result = result.compareTo(new BigDecimal("0E-8")) == 0 ? new BigDecimal("0") : result; return result; } //減法--引數為:Double,Double 四捨五入保留num位小數 public static BigDecimal subtract(Double num1, Double num2, int num) { BigDecimal result = BigDecimal.valueOf(num1).subtract(BigDecimal.valueOf(num2)).setScale(num, BigDecimal.ROUND_HALF_UP); result = result.compareTo(new BigDecimal("0E-8")) == 0 ? new BigDecimal("0") : result; return result; } //乘法--引數為:String,String 四捨五入保留num位小數 public static BigDecimal multiply(String num1, String num2, int num) { BigDecimal result = new BigDecimal(num1).multiply(new BigDecimal(num2)).setScale(num, BigDecimal.ROUND_HALF_UP); result = result.compareTo(new BigDecimal("0E-8")) == 0 ? new BigDecimal("0") : result; return result; } //乘法--引數為:Double,Double 四捨五入保留num位小數 public static BigDecimal multiply(Double num1, Double num2, int num) { BigDecimal result = BigDecimal.valueOf(num1).multiply(BigDecimal.valueOf(num2)).setScale(num, BigDecimal.ROUND_HALF_UP); result = result.compareTo(new BigDecimal("0E-8")) == 0 ? new BigDecimal("0") : result; return result; } //除法--引數為:String,String 四捨五入保留num位小數 public static BigDecimal divide(String num1, String num2, int num) { BigDecimal result = new BigDecimal(num1).divide(new BigDecimal(num2),num,BigDecimal.ROUND_HALF_UP); result = result.compareTo(new BigDecimal("0E-8")) == 0 ? new BigDecimal("0") : result; return result; } //除法--引數為:Double,Double 四捨五入保留num位小數 public BigDecimal divide(Double num1, Double num2, int num) { BigDecimal result = BigDecimal.valueOf(num1).divide(BigDecimal.valueOf(num2),num,BigDecimal.ROUND_HALF_UP); result = result.compareTo(new BigDecimal("0E-8")) == 0 ? new BigDecimal("0") : result; return result; }