Double decimal formatting in Java

To format a double value as a decimal in Java, you can use the DecimalFormat class from the java.text package. Here's an example of how to use it:

double value = 123.4567;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(value));

This will output 123.46, which is the value of value rounded to two decimal places.

You can specify the number of decimal places that you want by changing the pattern string passed to the DecimalFormat constructor. For example, to show four decimal places, you could use the pattern "#.0000".

Here are some other pattern examples:

  • "#,###.00" - displays the number with a comma as the thousands separator and two decimal places
  • "#.##%" - displays the number as a percentage with two decimal places
  • "\u00A4 #,##0.00" - displays the number with a currency symbol and two decimal places

You can find more information about the different pattern symbols and options in the DecimalFormat documentation.