java数值格式化方法

<div class="iteye-blog-content-contain" style="font-size: 14px">用于给数值格式化添加三进位逗号,</div> 首先会判断是否是数值,负数和乘方都可以使用
    private static String  decimalForamtTable(String str ){
        if(str !=null && str.trim().length() != 0 && str.matches("^-?[0-9]+(\\.[0-9]+)?([eE]?[+-]?[0-9]+)?$")){
            String[] strArr = new String[2];
            if(str.matches(".*\\..*")) {
                strArr = str.split("\\.");
                strArr[1] = "." + strArr[1];
            }else if(!str.matches(".*\\..*") && str.matches(".*[eE].*")){
                strArr = str.contains("e") ?  str.split("e") : str.split("E");
                strArr[1] = (str.contains("e") ? "e" : "E") + strArr[1];
            }else{
                strArr[0] = str;
            }
            String number = strArr[0].indexOf("-") == 0 ? strArr[0].replace("-",""):strArr[0] ;
            if(number.length()<4){
                return str;
            }
            String decimal = strArr[1] ;
            boolean negative = str.matches("^-.*$");
            DecimalFormat df = new DecimalFormat(",###");
            return (negative ? "-" : "" ) + df.format( Long.parseLong( number) )+ decimal;
        }else{
            return str;
        }
    }


测试: -123123.234234e+04
结果:-123,123.234234e+04

猜你喜欢

转载自banana1120.iteye.com/blog/2355541