package com.steerinfo.ems.Utils;

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

public class BigDecimalUtil {
	 // 默认除法运算精度
    private static final Integer DEF_DIV_SCALE = 2;
    
    /**
     * 提供精确的加法运算。
     *
     * @param value1 被加数
     * @param value2 加数
     * @return 两个参数的和
     */
   public static  BigDecimal add(Double value1,Double value2 ) {
	   BigDecimal b1 = new BigDecimal(Double.toString(value1));
	   BigDecimal b2 = new BigDecimal(Double.toString(value2));
	   return b1.add(b2);
   }
   
   /**
    * 减法
    * @param value1
    * @param value2
    * @return
    */
   public static BigDecimal sub(Double value1,Double value2) {
	   BigDecimal b1 = new BigDecimal(Double.toString(value1));
	   BigDecimal b2 = new BigDecimal(Double.toString(value2));
	   return b1.subtract(b2);
   }
   
   /**
    * 提供精确的乘法运算。
    *
    * @param value1 被乘数
    * @param value2 乘数
    * @return 两个参数的积
    */
   public static BigDecimal mul(Double value1,Double value2) {
	   BigDecimal b1 = new BigDecimal(Double.toString(value1));
	   BigDecimal b2 = new BigDecimal(Double.toString(value2));
	   return b1.multiply(b2);
   }
   
   public static Float mul(Float value1,Float value2) {
	   BigDecimal b1 = new BigDecimal(Float.toString(value1));
	   BigDecimal b2 = new BigDecimal(Float.toString(value1));
	   return b1.multiply(b2).floatValue();
   }
   
   public static int mulOneHundred(Double value1) {
	   BigDecimal b1 = new BigDecimal(Double.toString(value1));
	   BigDecimal b2 = new BigDecimal(Double.toString(100));
	   return b1.multiply(b2).intValue();
   }
   
	/**
	 * 提供（相对）精确的除法运算。 当发生除不尽的情况时，由scale参数指定精度，以后的数字四舍五入。
	 * 
	 * @param dividend
	 *            被除数
	 * @param divisor
	 *            除数
	 * @param scale
	 *            表示表示需要精确到小数点以后几位。
	 * @return 两个参数的商
	 */
	public static BigDecimal divide(Double dividend, Double divisor, Integer scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(dividend));
		BigDecimal b2 = new BigDecimal(Double.toString(divisor));
		try {
			BigDecimal sum = b1.divide(b2, scale, RoundingMode.HALF_UP);
			return sum;
		} catch (ArithmeticException e) {
			return BigDecimal.ZERO;
		}

	}
  
	public static Float divide(Float dividend, Float divisor, Integer scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(dividend));
		BigDecimal b2 = new BigDecimal(Double.toString(divisor));
		try {
			b1.divide(b2, scale, RoundingMode.HALF_UP).floatValue();
		} catch (Exception e) {
			System.out.println("累计量为0");
		}
		return b1.divide(b2, scale, RoundingMode.HALF_UP).floatValue();
	}
  
}
