计算百分比工具类

###一 代码

public static String percentageConversion(long divisor, long dividend) {
    
    
        String percentage = "";// 接受百分比的值
        double y = divisor * 1.0;
        double z = dividend * 1.0;
        if (y == 0 || z == 0) {
    
    
            return "0.00%";
        }
        double result = y / z;

        DecimalFormat decimalFormat = new DecimalFormat("##.00%"); // ##.00%

        percentage = decimalFormat.format(result);
	// ##.00% 使用这种转换方式,整数位如果是0 则会被删除  即0.35% 会出现 .35%的情况
        char c = percentage.charAt(0);
        if (String.valueOf(c).equals(".")) {
    
    
            StringBuffer sb = new StringBuffer();
            sb.append("0").append(percentage);
            return String.valueOf(sb);
        }
        return percentage;
    }

###二 # 和 0 的区别

public static void main(String[] args) {
    
    
        DecimalFormat decimalFormat = new DecimalFormat("##.00"); // ##.00%
        String format = decimalFormat.format(00012.00);//12.00
        String format1 = decimalFormat.format(0.12);// .12
        DecimalFormat decimalFormat1 = new DecimalFormat("000.00");
        String format2 = decimalFormat1.format(012.00);  //012.00
    }

参考文章

猜你喜欢

转载自blog.csdn.net/wyzyysw/article/details/114133797