Java控制小数点的几个常用方法

import java.text.DecimalFormat;

public class NumberUtil {
    
    public static double decimalFormatD(int num, double d){
        String format = "0.";
        String result = "";
        double db;
        
        for(int i=0;i<num;i++)
            format = format.concat("0");
        
        DecimalFormat decimal = new DecimalFormat(format);
        result = decimal.format(d);
        db = Double.parseDouble(result);
        
        return db;
    }
    
    public static float decimalFormatF(int num, float f){
        String format = "0.";
        String result = "";
        float fl;
        
        for(int i=0;i<num;i++)
            format = format.concat("0");
        
        DecimalFormat decimal = new DecimalFormat(format);
        result = decimal.format(f);
        fl = Float.parseFloat(result);
        
        return fl;
    }

    
    public static String doubleToString(double f){       
        String s = "";
        double a = 0;
        
        while(f >= 1) {
            
            a = f%((double)10);
            
            s = String.valueOf((int)a) + s;
            f=(f - a)/10;
        }
        return s;
    }
}

你可能感兴趣的:(Java控制小数点的几个常用方法)