本文主要是介绍java计算正确率或百分比,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//方法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));
这篇关于java计算正确率或百分比的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!