0

I have written a java program that does exactly what it's supposed to, however, the answer needs to be rounded to 5 decimal places.

I've googled it a ton, but every post I see has a double input. This is a sumArea answer that needs to be rounded.

public class COSC_HW13
{
    // Main method
    public static void main(String[] args) 
    {
    // Create an array of four objects
    GeometricObject[] array = {new Circle(5), new Circle(8),
    new Rectangle(3, 4), new Rectangle(4, 2)};

    // Display results
    System.out.println("Total area of elements in array: " 
            + sumArea(array));
    }

    // Returns the sum of the areas of 
    //all the geometric objects in an array
    public static double sumArea(GeometricObject[] a) 
    {
        double sum = 0;
        for (int i = 0; i < a.length; i++) 
        {
            sum += a[i].getArea();

        }
        return sum;
    }

}
Noah_J34
  • 1
  • 2

1 Answers1

0

You can use the DecimalFormat class from java.text.DecimalFormat. Below is what you'll need to do:

  1. import DecimalFormat: import java.text.DecimalFormat
  2. Setup a DecimalFormat object : DecimalFormat df = new DecimalFormat("#.#####");
  3. Use the object to format your number: df.format(sumArea(array))

As an example, df.format(5.123456) will return 5.12346 since 5 is rounded to 6.

CodeHat
  • 384
  • 4
  • 14