如何将数学答案四舍五入到小数点后五位

时间:2019-10-27 19:50:00

标签: java decimal rounding

我编写了一个Java程序,该程序完全可以实现预期的目标,但是答案必须四舍五入到小数点后5位。

我已经用谷歌搜索了很多,但是我看到的每个帖子都有两次输入。这是一个sumArea答案,需要四舍五入。

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;
    }

}

1 个答案:

答案 0 :(得分:0)

您可以使用DecimalFormat中的java.text.DecimalFormat类。以下是您需要做的事情:

  1. 导入DecimalFormat:import java.text.DecimalFormat
  2. 设置DecimalFormat对象:DecimalFormat df = new DecimalFormat("#.#####");
  3. 使用对象格式化您的电话号码:df.format(sumArea(array))

例如,由于5舍入到6,df.format(5.123456)将返回5.12346