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

后端 未结 5 1054
时光取名叫无心
时光取名叫无心 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:10

    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

提交回复
热议问题