Format Number with Commas in Java

Format number with Commas in Java

In this post, we will see how to format number with commas in java.

How To Add Commas to Number in Java

There are multiple ways to format number with commas in java. Let’s go through them.

1. Using DecimalFormat

DecimalFormat can be used by providing formatting Pattern to format number with commas in java.
Here is an example:

Output:

Formatted number with commas: 2,000,000.00

2. Using String’s format() method

You can also use String’s static method format() to format number with commas in java. This method is similar to System.out.printf.
Here is an example:

Output:

Formatted number with commas: 2,000,000.00

For format String "%,.2f" means separate digit groups with commas and ".2" means round number to 2 decimal places in java.

3. Using System.out.printf

If you want to print number with commas, this is best way to print number with commas on console.
Here is an example:

Output:

Formatted number with commas: 2,000,000

4. Using Formatter

You can use java.util.Formatter‘s format() method to format number with commas in java. This is similar to System.out.printf method.
Here is an example:

Output:

Formatted number with commas: 2,000,000.00

5. Using NumberFormat

You can also use NumberFormat‘s setMaximumFractionDigits() to put constraint on number by decimal places and use its format() method to format number with commas in java.
Here is an example:

Output:

Formatted number with commas: 2,000,000

That’s all about How to format number with commas in java

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *