Skip to content Skip to sidebar Skip to footer

How Can I Format A Number To The Fixed Locale?

How can I insert to a string comma (,) after every 3 position starting from last? input desired output 9876567846678 9,876,567,846,678 567 56

Solution 1:

Yes, there is a "trick" in Java:

publicstatic String addCommas(int num) {
    DecimalFormatdf=newDecimalFormat();
    DecimalFormatSymbolsdfs=newDecimalFormatSymbols();
    dfs.setGroupingSeparator(',');
    df.setDecimalFormatSymbols(dfs);
    return df.format(num);
}

System.out.println(addCommas(123456789));

EDIT: In case you want your output to be independent from locale you can use the method below. It starts from the end so there is no need to reverse the string and should be quite efficient:

publicstatic String addCommas(int num) {
    StringBuilders=newStringBuilder(Integer.toString(num));
    for(inti= s.length() - 3; i > 0; i -= 3) {
        s.insert(i, ',');
    }
    return s.toString();
}

Solution 2:

Have a look at the NumberFormat class, which is entirely used for formatting numbers as textual output.

In particular, an instance of DecimalFormat using the , symbol for separators is what you're looking for. A format pattern of #,##0 for example should output integers as you desire if you have no other constraints.

Solution 3:

Well, you could also use a StringBuilder to do that. Here's a quickly hacked together solution:

StringBuilder sb = new StringBuilder("123456789");

        int initLength = sb.length();
        for(int i=1; i<initLength; i++){
            if(i % 3 == 0){
                sb.insert(initLength-i, ",");
            }
        }

        System.out.println(sb);

Post a Comment for "How Can I Format A Number To The Fixed Locale?"