Java --计算百分比

时间:2023-03-08 19:19:41

Learn From: http://blog.****.net/maggiehexu/article/details/6387636

方法一:

public String getPercent(int x,int total){
String result = "";//接受百分比的值
double x_double = x*1.0;
double tempresult = x/total;
DecimalFormat df1 = new DecimalFormat("0.00%"); //##.00% 百分比格式,后面不足2位的用0补齐
result= df1.format(tempresult);
return result;
}

方法二:

public String getPercent(int x,int total){
String result = "";//接受百分比的值
double x_double = x*1.0;
double tempresult = x/total;
NumberFormat nf = NumberFormat.getPercentInstance();
nf.setMinimumFractionDigits(2);
result=nf.format(tempresult);

return result;
}