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.
Table of Contents
1. Using DecimalFormat
DecimalFormat can be used by providing formatting Pattern to format number with commas in java.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog; import java.text.DecimalFormat; public class FormatNumberWithCommaDecimalFormat { public static void main(String[] args) { DecimalFormat df=new DecimalFormat("#,###.00"); double d = 2000000; String formattedNumberWithComma = df.format(d); System.out.println("Formatted number with commas: "+formattedNumberWithComma); } } |
Output:
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class FormatNumberWithCommaStringFormat { public static void main(String[] args) { double d = 2000000; String formattedNumberWithComma = String.format("Formatted number with commas: %,.2f", d); System.out.println(formattedNumberWithComma); } } |
Output:
For format String "%,.2f" means separate digit groups with commas and ".2" means round number to 2 decimal places in java.
Further reading:
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class PrintNumberWithCommas { public static void main(String[] args) { double d = 2000000; System.out.printf("Formatted number with commas: %,.0f ",d); } } |
Output:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog; import java.util.Formatter; public class FormatterFormatNumberWithCommas { public static void main(String[] args) { double d = 2000000; Formatter formatter = new Formatter(); formatter.format("%,.2f", d); System.out.println("Formatted number with commas: " + formatter.toString()); } } |
Output:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; import java.text.NumberFormat; public class FormatNumberWithCommansNumberFormat { public static void main(String[] args) { double d = 2000000; NumberFormat nf= NumberFormat.getInstance(); nf.setMaximumFractionDigits(0); System.out.println("Formatted number with commas: " +nf.format(d)); } } |
Output:
That’s all about How to format number with commas in java