Java中计算百分比(DecimalFormat是NumberFormat的一个具体子类,用于格式化十进制数字)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZHOU_VIP/article/details/83059444
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)方法实现四舍五入。


 

猜你喜欢

转载自blog.csdn.net/ZHOU_VIP/article/details/83059444