Java中如何编写一个计算百分比的工具类呢?
下文笔者讲述java中计算百分比工具类的方法分享,如下所示
编写百分比工具类的实现思路
public static String percentageConversion(long divisor, long dividend) {
String percentage = "";// 接受百分比的值
double y = divisor * 1.0;
double z = dividend * 1.0;
if (y == 0 || z == 0) {
return "0.00%";
}
double result = y / z;
DecimalFormat decimalFormat = new DecimalFormat("##.00%"); // ##.00%
percentage = decimalFormat.format(result);
// ##.00% 使用这种转换方式
//整数位如果是0 则会被删除 即0.75% 会出现.75%的情况
char c = percentage.charAt(0);
if (String.valueOf(c).equals(".")) {
StringBuffer sb = new StringBuffer();
sb.append("0").append(percentage);
return String.valueOf(sb);
}
return percentage;
}
例:百分比的转换示例
#和0区别说明
public static void main(String[] args) {
DecimalFormat decimalFormat = new DecimalFormat("##.00"); // ##.00%
String format = decimalFormat.format(00023.00);//23.00
String format1 = decimalFormat.format(0.23);// .23
DecimalFormat decimalFormat1 = new DecimalFormat("000.00");
String format2 = decimalFormat1.format(023.00); //023.00
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


