package com.dev.swms.server.utils;

import java.math.BigDecimal;

import com.dev.swms.server.service.GlobalParamUtils;

/**
 *@author  dev
 */
public class DoubleUtils{

	/**
	 * 将一个数字的字符串，格式化为标准的三位小数的显示方式并且四舍五入
	 * @param a
	 * @return
	 */
	public static double format3Fraction(Object a) {
		return formatByPrecision(a,3);
	}
	
	public static double format2Fraction(Object a){
		return formatByPrecision(a,2);
	}
	
	public static double format1Fraction(Object a){
		return formatByPrecision(a,1);
	}
	
	public static double formatByPrecision(Object o,int precision){
		double pDouble = Double.parseDouble(o.toString());
		BigDecimal  bd = new  BigDecimal(pDouble);
		BigDecimal  bdWithPrecision = bd.setScale(precision,BigDecimal.ROUND_HALF_UP);
		pDouble = bdWithPrecision.doubleValue();
		return pDouble;
	}
	
	public static double formateByDefaultPrecesion(Object o){
		int pre = Integer.valueOf(GlobalParamUtils.getGloableStringValue("maintainTableDecimal")).intValue();
		return formatByPrecision(o,pre);
	}

	public static int compareByPrecision(Double source, Double target, int precision) {
		BigDecimal src = (new BigDecimal(source.toString())).setScale(precision,BigDecimal.ROUND_HALF_UP);
		BigDecimal dst = (new BigDecimal(target.toString())).setScale(precision,BigDecimal.ROUND_HALF_UP);
		
		return src.compareTo(dst);
	}

}
