import java.math.BigDecimal;
public class jamesMath {
private static final int DEF_DIV_SCALE = 10;
public static double round(double v,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 兩個Double數相加
* @param v1
* @param v2
* @return double
*/
public static double add(Double v1,Double v2){
BigDecimal b1 = new BigDecimal(v1.toString());
BigDecimal b2 = new BigDecimal(v2.toString());
return b1.add(b2).doubleValue();
}
/**
* 兩個Double數相減
* @param v1
* @param v2
* @return double
*/
public static double sub(Double v1,Double v2){
BigDecimal b1 = new BigDecimal(v1.toString());
BigDecimal b2 = new BigDecimal(v2.toString());
return b1.subtract(b2).doubleValue();
}
/**
* 兩個Double數相乘
* @param v1
* @param v2
* @return double
*/
public static double mul(Double v1,Double v2){
BigDecimal b1 = new BigDecimal(v1.toString());
BigDecimal b2 = new BigDecimal(v2.toString());
return b1.multiply(b2).doubleValue();
}
/**
* 兩個Double數相除
* @param v1
* @param v2
* @return double
*/
public static double div(Double v1,Double v2){
BigDecimal b1 = new BigDecimal(v1.toString());
BigDecimal b2 = new BigDecimal(v2.toString());
return b1.divide(b2,DEF_DIV_SCALE,BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 兩個Double數相除,並保留scale位小數
* @param v1
* @param v2
* @param scale
* @return double
*/
public static double div(Double v1,Double v2,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(v1.toString());
BigDecimal b2 = new BigDecimal(v2.toString());
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
沒有留言:
張貼留言