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";
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
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:
Examplepublic 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.
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.