To convert a double
value to a String
with a comma as the decimal separator in Java, you can use the DecimalFormat
class from the java.text
package.
Here's an example of how to do this:
double d = 12345.678; // Create a DecimalFormat object with a pattern that includes a comma as the decimal separator DecimalFormat df = new DecimalFormat("#,##0.00"); // Use the format() method to convert the double to a String String str = df.format(d); // str is now "12,345.68"
This will convert the double
value to a String
with a comma as the decimal separator and two decimal places.
You can specify a different pattern in the DecimalFormat
constructor to control the formatting of the double
value. For example, you can use the #
symbol to represent optional digits, the 0
symbol to represent required digits, and the ,
symbol to add a comma as a thousand separator.
It's important to note that the DecimalFormat
class is not thread-safe and should be used with caution in multi-threaded environments. Alternatively, you can use the NumberFormat
class from the java.text
package or the String.format()
method to convert a double
to a String
with a comma as the decimal separator.