The way to insert commas in large numbers

Is there a method that already exists, and if a method cannot be written that can format large numbers and insert commas in them?

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


public String insertCommas(Integer largeNumber) {

}
+3
source share
5 answers

With the help NumberFormatyou can do it 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 come out:

100
1,000
1,000,000
+3
source

You can use NumberFormat#getNumberInstancewith Locale.US:

Locale , . , - Locale . , - - , , , .


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

:

10,000,000

: Java 7 int : 1_000_000.

+5

DecimalFormat ( NumberFormat)? .

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

, .

+2

java.text.NumberFormat?

0

I tried to be very clear with what I am doing, it can do much less lines.

The algorithm is simple, I change the input line, and then break the number with a regular expression, in each match we add a comma.

If the module of size 3 is zero (e.g. 123456), we must remove the last comma.

Now we restore the original row order, again changing it, 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;
}
0
source

All Articles