To add commas to a number in Java, you can use the DecimalFormat
class and the format
method to format the number as a string with the desired number of decimal places and the use of a comma as the thousands separator.
Here is an example of how you can add commas to a number in Java:
double num = 1234567.89; // Create a DecimalFormat with 2 decimal places and a comma as the thousands separator DecimalFormat df = new DecimalFormat("#,##0.00"); // Format the number as a string with commas String str = df.format(num); // Print the formatted string System.out.println(str); // Output: 1,234,567.89
In this example, the DecimalFormat
object is created with a pattern string that specifies the desired number of decimal places (2) and the use of a comma as the thousands separator.
Then, the format
method of the DecimalFormat
object is used to format the number as a string with the specified pattern.
The resulting string contains the number with the desired number of decimal places and the use of a comma as the thousands separator.
It is important to note that the DecimalFormat
class is part of the java.text
package, and you need to import it in your code to use it.
It is also important to note that the DecimalFormat
class uses the default locale of the Java virtual machine to determine the format of the number, including the symbol used as the decimal separator and the symbol used as the thousands separator.
For example, in the United States, the default locale uses a period (.) as the decimal separator and a comma (,) as the thousands separator.
If you want to use a different locale or a different format for the number, you can specify the desired locale or format pattern when creating the DecimalFormat
object.
For example, to use a period (.) as the thousands separator and a comma (,) as the decimal separator, you can use the following pattern string: "#.##0,00"