Social Icons

Monday, December 24, 2012

Comma separation code in Java

Displaying large figures without comma separation is quite daunting to the users. For an example just think how hard to discern the value of 9501625237.56 ? Instead of displaying such number as it is we can format the said value using commas which would be more readable , like this  9,501,625,237.56 If displayed likewise An user wouldn't have to waste time deciphering such lengthy values. Here is the code I wrote to accomplish this output using Java to utilize into much larger programs. The method can be overridden or overloaded as you would deem necessary. 

Input : Takes the value to be formatted as a  String object.
Returns: Formatted value as a String object.
private String addCommas(String strn){

         String commaSeparatedNumber="", decimals="";
        //split contents before the decimal point

        commaSeparatedNumber = strn.contains(".") ?   strn.split("\\.")[0] : strn;
        decimals = strn.contains(".") ? "."+strn.split("\\.")[1] : "";

        /*create a regular expression for the thousand separator, store those matches separately for the replacement.*/
        String regx="(\\d+)(\\d{3})";

        //create pattern and matcher objects to find matches
        Pattern p = Pattern.compile(regx);
        Matcher m = p.matcher(commaSeparatedNumber);

        //iterate to find the next match.
            //replace the found matching groups with the comma.
            commaSeparatedNumber = commaSeparatedNumber.replaceFirst(regx, +","+;
            //update the matcher with new replacements.
            m = p.matcher(commaSeparatedNumber);

        return commaSeparatedNumber+decimals;

Blogger Templates