Java 基础,小数百分比两种方法

public static void main(String[] args) {
        System.out.println(getPercent(1, 2));
    }

    public static String getPercent(double x, double total) {
        DecimalFormat df = new DecimalFormat("0.00%");// ##.00% 百分比格式,后面不足2位的用0补齐
        double result = x / total;
        return df.format(result);
    }

    public static String getPercent(int x, int total) {
        String result = "";// 接受百分比的值
        double x_double = x * 1.0;
        double tempresult = x_double / total;
        System.out.println(tempresult);
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(3); // 保留到小数点后几位
        return nf.format(tempresult);
    }

注意:先把其中一个参数转换为double才能获取到小数部分