1. 程式人生 > >java中保留double小數位的幾種方法

java中保留double小數位的幾種方法

	public static void main(String[] args) {
		//方法一   這個的優勢是得出的double  使用這個方法還有個問題當num=4.015得到的值是4.01  下面兩種方法的結果是4.02
		double num = 4.016;
		double v1 = (double)Math.round(num*100)/100;
		System.out.println(v1);
		//輸出 4.02
		
		//方法二
		num = 4.016;
		DecimalFormat formater = new DecimalFormat();
		//保留幾位小數
        formater.setMaximumFractionDigits(2);
        //模式  四捨五入
        formater.setRoundingMode(RoundingMode.UP);
        System.out.println(formater.format(num));
        //輸出4.02
        
        //方法三   這個方法如果設定scale為0  依然保留一位小數*.0
        num = 4.016;
		System.out.println(round(num, 2));
		//輸出 4.02
	}
	
	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();    
	}