Add commas (grouping separator) to number without

2019-04-05 08:28发布

I'm trying to format a string to add commas between 3 digit groups

EG:

1200.20 >> 1,200.20
15000   >> 15,000

I'm trying to figure out how to do it with DecimalFormat, to this point I have been using a script of my own that seems overly complicated. I cannot figure out how to do it, using # simply hides trailing zeroes and using 0 adds them to the number.

This is what I'm trying right now:

DecimalFormat df = new DecimalFormat("###,###.####", new DecimalFormatSymbols(Locale.US));
resultStr = df.format(Double.valueOf(resultStr));

I'm sure it must be easy but I'm not sure how to do it. I don't have to do it with DecimalFormat, I just thought it would be the easier way. How can I simply add the commas without modifying the decimals in any way?

5条回答
家丑人穷心不美
2楼-- · 2019-04-05 08:40

You should use a NumberFormat object and set it to use grouping. Something like

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class NumberFormatEg {
   public static void main(String[] args) {
      NumberFormat myFormat = NumberFormat.getInstance();
      myFormat.setGroupingUsed(true);

      double[] numbers = { 11220.00, 232323232.24, 121211.55, 102.121212 };

      for (double d : numbers) {
         System.out.println(myFormat.format(d));
      }
      System.out.println();

      DecimalFormat decimalFormat = new DecimalFormat("#.00");
      decimalFormat.setGroupingUsed(true);
      decimalFormat.setGroupingSize(3);

      for (double d : numbers) {
         System.out.println(decimalFormat.format(d));
      }

      System.out.println("\nFor Germany");

      NumberFormat anotherFormat = NumberFormat
            .getNumberInstance(Locale.GERMAN);
      if (anotherFormat instanceof DecimalFormat) {
         DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
         anotherDFormat.applyPattern("#.00");
         anotherDFormat.setGroupingUsed(true);
         anotherDFormat.setGroupingSize(3);

         for (double d : numbers) {
            System.out.println(anotherDFormat.format(d));
         }

      }

      System.out.println("\nFor US:");

      anotherFormat = NumberFormat.getNumberInstance(Locale.US);
      if (anotherFormat instanceof DecimalFormat) {
         DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
         anotherDFormat.applyPattern("#.00");
         anotherDFormat.setGroupingUsed(true);
         anotherDFormat.setGroupingSize(3);

         for (double d : numbers) {
            System.out.println(anotherDFormat.format(d));
         }

      }
   }
}

which returns:

11,220
232,323,232.24
121,211.55
102.121

11,220.00
232,323,232.24
121,211.55
102.12

For Germany
11.220,00
232.323.232,24
121.211,55
102,12

For US:
11,220.00
232,323,232.24
121,211.55
102.12

An advantage of this is that the solution can be locale specific.

Edited
Now shows an example with a DecimalFormat object. Note that you should set the grouping size if you use this.

查看更多
虎瘦雄心在
3楼-- · 2019-04-05 08:43

You can also try something like

DecimalFormat df = new DecimalFormat("#,###.00");

System.out.println(df.format(1200.20));
System.out.println(df.format(15000));
System.out.println(df.format(123456789.99));
1,200.20
15,000.00
123,456,789.99
查看更多
ゆ 、 Hurt°
4楼-- · 2019-04-05 08:46

The most simple solution

Why don't you use the comma , flag with printf.

System.out.printf( "%,d\n", 58625 );// the d to accept decimal integer
System.out.printf( "%,.2f", 12345678.9 );// the f to accept folouting point and 2 to take only 2 digits  

The output will be

58,625
12,345,678.90

And the good news: The actual generated separator used is specific to the user’s locale

查看更多
姐就是有狂的资本
5楼-- · 2019-04-05 08:56

You should be able to do exactly what you want:

http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

DecimalFormat myFormatter = new DecimalFormat("$###,###.###");
String output = myFormatter.format(12345.67);
System.out.println(value + " " + pattern + " " + output);
查看更多
叛逆
6楼-- · 2019-04-05 08:59

I couldn't make any of the other solutions work, some round the decimals, some add trailing zeroes or some remove trailing zeroes.

I don't plan of accepting my own answer but I'll post my script in case somebody finds it useful.

public void(String str) {
    int floatPos = str.indexOf(".") > -1 ? str.length() - str.indexOf(".") : 0;
    int nGroups= (str.length()-floatPos-1-(str.indexOf("-")>-1?1:0))/3;
    for(int i=0; i<nGroups; i++){
        int commaPos = str.length() - i * 4 - 3 - floatPos;
    str = str.substring(0,commaPos) + "," + str.substring(commaPos,str.length());
    }
    return str;
}


1             => 1
1.0           => 1.0
1234.01       => 1,234.01
1100100.12345 => 1,100,100.12345
查看更多
登录 后发表回答