记一次千分位代码的处理
由于业务需求 数字的展示需要写成千分位的处理
private static final Pattern NUMBER_PATTERN = Pattern.compile("^-?(\\d*\\.\\d*$)|(\\d*)$");
private static final Pattern PERCENT_NUMBER_PATTERN = Pattern.compile("^-?(\\d*\\.\\d*%$)|(\\d*)%$");
public static final String PERCENT = "%";
public static final String COMMA = ",";
public static final String DROP = ".";
/**
* 千分位处理
* @return String
*/
public static String thousandthPercentile(String number){
//判断字符串不为空 或者不是数字(允许是百分比数字)
if (!StringUtils.hasText(number) || !(NUMBER_PATTERN.matcher(number).matches() || PERCENT_NUMBER_PATTERN.matcher(number).matches())) {
return number;
}
StringBuilder reverse = new StringBuilder(number).reverse();
int index = reverse.indexOf(DROP) + 1;
if(number.lastIndexOf(PERCENT) == number.length()){
//如果是已%结尾的前移一位
index = index + 1;
}
int i = 3 + index;
while ((reverse.length()) > i){
reverse.insert(i, COMMA);
i = i + 4;
}
reverse = reverse.reverse();
if(reverse.lastIndexOf(COMMA) == reverse.length()){
//最后一个不能为 -,
return reverse.substring(0, reverse.length() - 2);
}
return reverse.toString().replaceAll("-,", "-");
}