项目中会设计一些统计 百分比 的数据内容。
有两种情况, 一种是 用字符串显示百分比 , 如45.56%
此时使用:
NumberFormat nt = NumberFormat.getPercentInstance();
//设置百分数精确度2即保留两位小数 没有考虑任务数量为0的情况
nt.setMinimumFractionDigits(0);
//计算百分比
float accounted = 0F;
// 保证分母不为0 (注意violationSum 的类型,是double还是integer)
if(violationSum != 0)
{
accounted = Integer.valueOf(violationNumber/violationSum);
}
还有一种情况是, 给前端的百分比是 数字类型,并且保留两位字符串, 如: 0.45
此时使用:
// 保留两位小数
BigDecimal twoAccountedComplate = new BigDecimal(accountedComplate);
BigDecimal twoAccountedTimeout = new BigDecimal(accountedTimeout);
countryList.get(i).put("accountedComplate" ,twoAccountedComplate.setScale(2, RoundingMode.HALF_UP));
countryList.get(i).put("accountedTimeout" ,twoAccountedTimeout.setScale(2, RoundingMode.HALF_UP));
使用 setScale(2, RoundingMode.HALF_UP) 可以让bigDecimal保留两位小数