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 ); 保留到小数点后几位
DecimalFormat df1 = new DecimalFormat("0.00%"); //##.00% 百分比格式,后面不足2位的用0补齐
//result=nf.format(tempresult);
result= df1.format(tempresult);
return result;
}
https://blog.csdn.net/shehun11/article/details/42141923
https://blog.csdn.net/lyh147406/article/details/76165947
https://blog.csdn.net/u011106915/article/details/75361276
https://blog.csdn.net/u014704879/article/details/41479399/
DecimalForma函数默认的四舍五入的方法是银行家算法。跟一般的四舍五入的方法不同。
银行家算法:四舍六入五考虑,五后非零就进一,五后为零看奇偶,五前为偶应舍去,五前为奇要进一。
DecimalFormat 提供 RoundingMode 中定义的舍入模式进行格式化。默认情况下,它使用 RoundingMode.HALF_EVEN,
要想实现正常的四舍五入,需要调用decimalFormat.setRoundingMode(RoundingMode.HALF_UP)方法实现四舍五入。
本文介绍了一种在Java中将整数转换为百分比字符串的方法,并详细解释了DecimalFormat类的使用,包括如何应用不同的格式化模式和RoundingMode来实现银行家算法或标准的四舍五入。
&spm=1001.2101.3001.5002&articleId=83059444&d=1&t=3&u=1aa6ba3d57444b0d826b92e9fee210cd)
1899

被折叠的 条评论
为什么被折叠?



