Being able to round a real number (double number) off to a certain number of decimal places will be required in both the grade 11 and 12 practical exams.

For this, you will need to import the DecimalFormat class. Then you must create a DecimalFormat object that specifies the number of decimal places that you require (line 14).

Note that DecimalFormat works with a String – you cannot use it directly with a double value (see line 21). Line 19 works because System.out.println( ”  ” + will ensure that the rest of the line of code is automatically cast to String (including the double).

Alternative: Lines 23, 24 and 25 manually cast the double to String before rounding the number.

You can use the “format” method of the DecimalFormat object to round any double number that you may have in your code.

Click here