//方法1
public static String accuracy(double num, double total, int scale){
DecimalFormat df = (DecimalFormat)NumberFormat.getInstance();
//可以设置精确几位小数
df.setMaximumFractionDigits(scale);
//模式 例如四舍五入
df.setRoundingMode(RoundingMode.HALF_UP);
double accuracy_num = num / total * 100;
return df.format(accuracy_num)+"%";
}
int num = 1;
int total = 100;
int scale = 1;
String result = accuracy(num, total, scale);
System.out.println(result);
//1%
int num = 1;
int total = 3;
int scale = 1;
String result = accuracy(num, total, scale);
System.out.println(result);
//33.3%
int num = 1;
int total = 1000;
int scale = 1;
String result = accuracy(num, total, scale);
System.out.println(result);
//0.1%
int num = 1;
int total = 10000;
int scale = 1;
String result = accuracy(num, total, scale);
System.out.println(result);
//0%
//方法二
//0表示的是小数点 之前没有这样配置有问题例如 num=1 and total=1000 结果是.1 很郁闷
DecimalFormat df = new DecimalFormat("0%");
//可以设置精确几位小数
df.setMaximumFractionDigits(1);
//模式 例如四舍五入
df.setRoundingMode(RoundingMode.HALF_UP);
int num = 1;
int total = 1000;
double accuracy_num = num * 1.0/ total * 1.0;
System.out.println(df.format(accuracy_num));