格式化数字,
1、自定义多少位千化数
2、以什么符号分割,
3、保留多少位小数。
使用方便灵活
两种方法,新增DecimalFormat格式化
一、DecimalFormat格式化
public static String formatNumberWithMarkSplit(double number) {
return formatNumberWithMarkSplit(number, ",", 3, 2);
}
public static String formatNumberWithMarkSplit(double number, int endLength) {
return formatNumberWithMarkSplit(number, ",", 3, endLength);
}
/**
* 格式化数字,用逗号分割
*
* @param number 1000000.7569 to 1,000,000.76 or
* @param splitChar 分割符号
* @param endLength 保存多少小数位
* @param splitLength 分割位数
* @return 格式化完成的字符串
*/
public static String formatNumberWithMarkSplit(double number, String splitChar, int splitLength, int endLength) {
StringBuilder tempSplitStr = new StringBuilder();
for (int index = 0; index < splitLength; index++) tempSplitStr.append("#");
StringBuilder tempPattern = new StringBuilder(tempSplitStr + splitChar + tempSplitStr.substring(0, splitLength - 1) + "0.");/*###,##0.*/
for (int index = 0; index < endLength; index++) tempPattern.append("0");
return new DecimalFormat(tempPattern.toString()).format(number);
}
二、自定义分割
/**
* 格式化数字,用逗号分割
*
* @param number 1000000.7569 to 1,000,000.76 or
* @return
*/
public static String formatNumberWithCommaSplit(double number) {
String firstStr = "";//第一个字符
String middleStr = "";//中间字符
String endStr = "";//小数后两位
if (number < 0) {
firstStr = "-";
} else if (number != 0 && number < 0.1) {
return number + "";
}
String tempNumberStr = number + "00000000000000000";
int endIndex = tempNumberStr.lastIndexOf(".");
endStr = tempNumberStr.substring(endIndex+1, endIndex + 3);
String numberStr = Math.abs((long) number) + "";//取正
int firstIndex = numberStr.length() % 3;
int bitCount = numberStr.length() / 3;
if (firstIndex > 0) {
middleStr += numberStr.substring(0, firstIndex) + ",";
}
for (int i = 0; i < bitCount; i++) {
middleStr += numberStr.substring(firstIndex + i * 3, firstIndex + i * 3 + 3) + ",";
}
if (middleStr.length() > 1) {
middleStr = middleStr.substring(0, middleStr.length() - 1);
}
return firstStr + middleStr + "." + endStr;
}