
注意:
1. 整数除法将四舍五入,并且小数点将不会保留. 您需要保留小数点并转换为浮点除法.
方法1: 使用字符串格式化

public static float computePercentage(float a, float total) {
if (a == 0 || total == 0) {
return 0;
} else {
//4表示保留两位小数,f表示float类型,
//乘100是因为我是求百分比,
return Float.parseFloat(String.format("%.4f", a / total)) * 100;
}
}
测试:System.err.println(computePercentage(141,173));
输出:81.5
方法二,使用java.text.NumberFormat,数字格式
NumberFormat nf = NumberFormat.getNumberInstance();

//设置保留的最大小数位数
nf.setMaximumFractionDigits(2);
float s =(float)141 /(float)173;

System.err.println(nf.format(s));
输出: 0.82
注意: NumberFormat还提供百分比java格式化小数,整数格式等.

方法三,使用DecimalFormat格式化
float s =(float)141 /(float)173;
//#: 想法是阿拉伯数字,如果不是,则不会显示. 0: 一个阿拉伯数字java格式化小数,不以0表示.
System.err.println(新的DecimalFormat(“ ##. 00%”). 格式);
输出: 81.50%
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-160650-1.html
一舰喊话
1