java计算每个元素出现的百分比_java计算正确率或百分比

这篇博客介绍了两种在Java中计算精度并格式化为百分比的方法。方法一使用DecimalFormat类,通过设置最大小数位数和舍入模式实现;方法二直接在格式字符串中指定小数位数。示例代码展示了不同数值和比例下的百分比格式化结果。
摘要由CSDN通过智能技术生成

//方法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));

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值