/** * A simple Java example that converts a double to String using two decimal places via String.format(). */ public class Test { public static void main(String[] args) { double number = 123.4567d; String numberAsString = String.format ("%.2f", number); System.out.println(numberAsString); } }The parameter "%.2f" tells the formatter to use specifically two decimal places. When we run this, since there are more than 2 decimal places, it will be rounded. Hence the .45 will be .46 and the output will be:
123.46If we want to format using two decimal places and also separate thousands indicator using comma, we can do this also using String.format() method. Here is an example:
/** * A simple Java example that converts a double to String using two decimal places and using comma * as thousand separator via String.format(). */ public class Test { public static void main(String[] args) { double number = 189563245.4567d; String numberAsString = String.format ("%,.2f", number); System.out.println(numberAsString); } }The parameter "%,.2f" tells to use comma as thousand separator and 2 decimal digit when converting. The whole number is therefore comma separated for every 3 digits from the right. And the decimal digits are capped to two decimal places and rounding if necessary. Below is the output of the code:
189,563,245.46
/** * A simple Java example that converts a double to String using two decimal places via DecimalFormat. */ public class Test { public static void main(String[] args) { double number = 456.7891d; DecimalFormat decimalFormat = new DecimalFormat("#.00"); String numberAsString = decimalFormat.format(number); System.out.println(numberAsString); } }The ".00" in the parameter tells the formatter to use two decimal places while the "#" means to display the whole number as it is. The output is also rounded, which should be:
456.79
Similar to the previous method, we can also use DecimalFormat to also do thousand separator. Below is an example on how to do that using DecimalFormat:
/** * A simple Java example that converts a double to String using two decimal places and using comma * as thousand separator via DecimalFormat. */ public class Test { 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); } }Whole numbers are comma separated every three digit and the decimal place is rounded to two decimal. The output therefore is:
12,345,678.79