Being able to round a real number (double number) in Java off to a certain number of decimal places will be required in both the grade 11 and 12 practical exams.
NOTE: When rounding off using these String based methods the accuacy of the origial number does not changed.
Method one. Preferred. Using the DecimalFormat class
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.
Method Two. Using the format method inside the String class
double number = 12.2345678;
// Rounds to the nearest whole number
String formattedNumber0 = String.format(“%.0f”, number);
System.out.println(formattedNumber0);
// Rounds to one decimal place
String formattedNumber1 = String.format(“%.1f”, number);
System.out.println(formattedNumber1);
// Rounds to two decimal places
String formattedNumber2 = String.format(“%.2f”, number);
System.out.println(formattedNumber2);
// Rounds to three decimal places
String formattedNumber3 = String.format(“%.3f”, number);
System.out.println(formattedNumber3);