Double算数运算

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class Arith {
	 private static final int DEF_DIV_SCALE = 10;
	    
	    /**
	     * 两个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();
	    }
	    
	    /**
	     * 兩個數相減,如果有小數就向上進值.
	     * @param v1
	     * @param v2
	     * @return
	     */
	    public static Double subtract(Double v1,Double v2){
	    	BigDecimal b1 = new BigDecimal(v1.toString());
	        BigDecimal b2 = new BigDecimal(v2.toString());
	        return b1.subtract(b2,new MathContext(1,RoundingMode.CEILING)).doubleValue();
	    }

	    /**
	     * 對數值進行取值的優化.
	     * @param v1 
	     * @param scale 取小數點后位數。
	     * @return
	     */
	    public static Double getSacleDouble(Double v1,int scale){
	    	BigDecimal b1 = new BigDecimal(v1.toString());
	    	return b1.setScale(scale,BigDecimal.ROUND_HALF_UP).doubleValue();   
	    }
	    
	   public static void main(String args[]){
		   System.out.println(sub(1000d,2000d));
	   }
	} 

 

你可能感兴趣的:(UP)