Formatting Decimal numbers for output:
Formatting a number before it is printed involves following a number of steps.
import java.text.*;
public class Class1 {
public static void main (String[] args) {
double number = 912.3465;
DecimalFormat x = new DecimalFormat("#####.##");
System.out.println (x.format(number));
}
}
The steps required for formatting a number:
import java.text.*;
2. Create a "DecimalFormat" object that is used for formatting the number.
DecimalFormat x = newDecimalFormat("#####.##");
The above line creates the object "x" that will be used to format a decimal number to two decimals places with 5 digits before the decimal.
DecimalFormat y = newDecimalFormat("#,###,###.###");
The above line creates the object "y" that will be used to format a decimal number to three decimals places with 7 digits before the decimal and commas between each group if three digits.
Example:
System.out.println (x.format(123.45678) );
The above line of code prints out the following:
912.35