Add commas (grouping separator) to number without modifying decimals?

后端 未结 5 1043
时光取名叫无心
时光取名叫无心 2020-12-16 00:55

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 tryi

5条回答
  •  爱一瞬间的悲伤
    2020-12-16 01:17

    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.

提交回复
热议问题