Domanda

Is there a method that already exists and if not can a method be written that can format large numbers and insert commas into them?

100     = 100
1000    = 1,000  
10000   = 10,000
100000  = 100,000
1000000 = 1,000,000


public String insertCommas(Integer largeNumber) {

}
È stato utile?

Soluzione

With NumberFormat you can do this easily:

NumberFormat format = NumberFormat.getInstance(Locale.US);

System.out.println(format.format(100));
System.out.println(format.format(1000));
System.out.println(format.format(1000000));

will ouput:

100
1,000
1,000,000

Altri suggerimenti

You can use NumberFormat#getNumberInstance with Locale.US:

A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation— the number should be formatted according to the customs and conventions of the user's native country, region, or culture.


System.out.println(NumberFormat.getNumberInstance(Locale.US).format(10000000));

This will print:

10,000,000

Side note: In Java 7, you can write an int with underscores: 1_000_000.

Have you looked at DecimalFormat (a derivation of the abstract NumberFormat)? You can customise the format to your needs.

DecimalFormat myFormatter = new DecimalFormat("###,###.###");
String output = myFormatter.format(value);

Note also that you can determine formatting based upon the locale.

Have you tried java.text.NumberFormat?

I tried to be very clear with what i'm doing, it could be done in much less lines.

The algorithm is simple, i reverse the input string, then i split the number using a regex, in each match we add a comma.

If the number size module 3 is zero (for example 123456) we have to remove the last comma.

Now we restore original string order by reversing it again, and voilá.

public String insertCommas(Integer largeNumber) {

    String result;
    String reversedNum = new StringBuilder(""+largeNumber).reverse().toString();
    String reversedResult = "";

    Pattern pattern = Pattern.compile("\\d{3}");
    Matcher matcher = pattern.matcher(reversedNum);

    int lastIndex = reversedNum.length();
    while(matcher.find()){
        reversedResult += matcher.group()+",";
        lastIndex = matcher.end();
    }

    String remaining = reversedNum.substring(lastIndex);
    reversedResult += remaining; 
    result =  new StringBuilder(reversedResult).reverse().toString();
    if(remaining.isEmpty()){
        result =  new     StringBuilder(reversedResult).reverse().toString().substring(1);
    }else{
        result =  new StringBuilder(reversedResult).reverse().toString();
    }

    return result;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top