Numeric String Formatting

Floating point numeric values expressed as a String (e.g. output from System.out.println()) will display decimal places - but you can't control how many. You can control the number of decimal places displayed by making use of a special Java class. Do the following:

1. import java.text.DecimalFormat;

2. Create a DecimalFormat object as follows:

DecimalFormat df = new DecimalFormat("#.0000"); // 4 decimal places

3. When you want to create a String representation of a number as specified by the DecimalFormat object, pass it to the format() method of this object, for example:

System.out.println("Number is " + df.format(adouble));

The format() method takes a double and returns a String, which is the text representation of the double's value, formatted as specified in the constructor of the DecimalFormat object. Think about this if you need to until you understand it.

Other formatting variations are possible, of course. Look at the documentation for both NumberFormat and DecimalFormat.