/** * This is a simple Java example that converts a double to String using two decimal places through DecimalFormat. */ public class DoubleToStringTest { public static void main(String[] args) { double number = 555.7891d; DecimalFormat decimalFormat = new DecimalFormat("#.00"); String numberAsString = decimalFormat.format(number); System.out.println(numberAsString); } }The "#" parameter shows the whole number, while the ".00" notifies the formatter about the two decimal places. The output shows the rounded number. Check the details below:
555.79We can also utilize the DecimalFormat as a thousand separator, let's observe the process in the given example:
/** * This is a simple Java example that converts a double to String using two decimal places and using comma * as thousand separator through DecimalFormat. */ public class DoubleToStringTest { public static void main(String[] args) { double number = 12345678.7891d; DecimalFormat decimalFormat = new DecimalFormat("#,##0.00"); String numberAsString = decimalFormat.format(number); System.out.println(numberAsString); } }Not only we've converted the double variable number into a String, we also separated numbers with commas for every three digits. Let's not forget our rounded decimal places remained also.
12,345,678.79These are the important methods and parameters in converting double to a String using 2 decimal places.
/** * This is a simple Java example that converts a double to String using two decimal places through String.format(). */ public class DoubleToStringTest { public static void main(String[] args) { double number = 333.4567d; String numberAsString = String.format ("%.2f", number); System.out.println("This is the converted number: " + numberAsString); } }What the parameter "%.2f" does is notify the formatter to utilize exactly two decimal places. Since our variable number has more than 2 decimal places, the parameter will only acquire .45, and when we round of this number, our output will be .46, check out the result below:
This is the converted number: "333.46Let's now try the String.format with thousand indicator using comma and observe the written example below:
/** * This is a simple Java example that converts a double to String using two decimal places and using comma * as thousand separator through String.format(). */ public class DoubleToStringTest { public static void main(String[] args) { double number = 1098765432.4567d; String numberAsString = String.format ("%,.2f", number); System.out.println(numberAsString); } }The parameter "%,.2f" notifies us that the thousand separator is a comma, and the two decimal digit will retain once it is converted. Therefore for every 3 digits from the right, the whole number is now separated with a comma. And the two decimal places that has been rounded remained.
Check out the output shown below:
1,098,765,432.46