JavaDevNotes.com

Java Integer To String With Commas

This tutorial post will show how to convert Java Int to String with comma separator for every 3 digits (thousand separator). Example Java codes will be shared below.

Description

Given a number with more than 3 digits, we wish to convert it to a String instance that have commas every 3 digits from the right.

For example, if we have the number

int number = 1234567;
What we desire is to have a String with this equivalent value:
String numberAsString = "1,234,567";


Convert using NumberFormat

A very simple trick to solve this problem is to use NumberFormat.getNumberInstance(Locale.US).format(int) method. This is because the number instance for the US Locale will place the thousandth operator automatically. Here is an example code:

import java.text.NumberFormat;
import java.util.Locale;
public class Testing {
   public static void main(String[] args) {
      int number = 1234567;
      NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
      String numberAsString = numberFormat.format(number);
      System.out.println(numberAsString);
   }
}

The output is the expected outcome:
1,234,567


Convert using String.format()

If you are using Java 5 (JDK1.5) or higher, the String.format() static method can be used to convert an int to String with comma separator. This is simple and straightforward.

Syntax

public static String format(String format, Object... args)

If we use this plainly with this code:

int number = 1234567;
String numberAsString = String.format ("%d", number);

The variable numberAsString will have the value of "1234567"

But we can specify special formatting to have comma separator:

Example
This code snippet:
public class Testing {
   public static void main(String[] args) {
      int number = 1234567;
      String numberAsString = String.format("%,d", number);
      System.out.println(numberAsString);
   }
}
Will render this output:
1,234,567

As you can see, when we changed "%d" to "%,d", it tells the method to put comma separator for each 3 digits.



Convert using DecimalFormat

The class java.text.DecimalFormat is a class that formats a number to a String representation following a certain pattern. We can have this pattern put the required commas.

Example
Here is an example code

import java.text.DecimalFormat;
public class Testing2 {
   public static void main(String[] args) {
      int number = 1234567;
      DecimalFormat decimalFormat = new DecimalFormat("#,###");
      String numberAsString = decimalFormat.format(number);
      System.out.println(numberAsString);
   }
}
The output is the same as the examples above:
1,234,567



Read my previous post if you wish to see example code on general ways of converting a Java Int to String.


String Tutorials And Examples