直接上代码
/**
* zn
*
* @param obj 待转换的数值 只允许为Integer或者Double
* @param digits 保留小数的位数
* @param boolea 是否开启四舍五入 true:开启四舍五入 false:舍去多余位数
* @return
* @throws Exception
*/
public static String numFormat(Object obj, Integer digits, Boolean boolea) throws Exception {
if (obj == null || digits == null || boolea == null || digits < 0) {
throw new IllegalAccessException("参数列表有误");
}
Integer flag = obj instanceof Integer ? 1 : obj instanceof Double ? 2 : 3;
StringBuffer str = new StringBuffer();
switch (flag) {
case 1:
Integer integer = (Integer) obj;
str.append(integer + ".");
for (int i = 0; i < digits; i++) {
str.append(0);
}
break;
case 2:
Double aDouble = (Double) obj;
String[] split = String.valueOf(aDouble).split("\\.");
if (digits >= split[1].length()) {
str.append(split[0] + "." + split[1]);
for (int i = split[1].length(); i < digits; i++) {
str.append(0);
}
} else {
if (boolea) {
int num = Integer.parseInt(split[0] + split[1].substring(0, digits));
num += (split[1].charAt(digits) - 48) > 4 ? 1 : 0;
String s = String.valueOf(num);
if (digits == 0) {
str.append(s.substring(0, s.length() - digits) + s.substring(s.length() - digits, s.length()));
} else {
str.append(s.substring(0, s.length() - digits) + "." + s.substring(s.length() - digits, s.length()));
}
} else {
if (digits == 0) {
str.append(split[0] + split[1].substring(0, digits));
} else {
str.append(split[0] + "." + split[1].substring(0, digits));
}
}
}
break;
default:
throw new NumberFormatException("转换参数类型错误");
}
return str.toString();
}
网友评论