Java - How to put a comma (,) after every 3 digits

When expressing the amount, sometimes you want to put a comma (,) in every 3 digits.

10000 -> 10,000
12345 -> 12,345

How to use DecimalFormat

You can define the string format using DecimalFormat.

The string format is passed as an argument when creating a DecimalFormat object.

If you want to put a comma every 3 digits, set it in the format "###,###" as shown below.

DecimalFormat decFormat = new DecimalFormat("###,###");

String str = decFormat.format(12300000);
System.out.println(str);

str = decFormat.format(505000);
System.out.println(str);

Output:

12,300,000
505,000

decimal output

If you want to print decimals, just type in the format like ".##".

"###,###.##" means to put a comma in every 3 digits and to output only 2 decimal places.

NumberFormat numberFormat = NumberFormat.getInstance();

String str = numberFormat.format(123000);
System.out.println(str);

str = numberFormat.format(123000.7891);
System.out.println(str);

Output:

123,000
123,000.79

How to use NumberFormat

You can use NumberFormat to put commas in numbers.

NumberFormat formats the string in the notation used by the set Locale.

If you do not pass the Locale argument to getInstance() when creating a NumberFormat object, Locale.US is set as the default value, and commas are placed every 3 digits according to the US number notation.

NumberFormat numberFormat = NumberFormat.getInstance();

String str = numberFormat.format(123000);
System.out.println(str);

str = numberFormat.format(123000.7891);
System.out.println(str);

Output:

123,000
123,000.789

If you want to output in the number notation of another country, you can pass Locale as an argument when creating NumberFormat.

NumberFormat numberFormat = NumberFormat.getInstance(Locale.ITALY);

NumberFormat numberFormat2 = NumberFormat.getInstance(Locale.CHINA);
codechachaCopyright ©2019 codechacha