Search code examples
javaarraysdoubledecimal-point

Java: How to round up all of the elements in an array to two digits after decimal point?


I have a problem with rounding double values from an array.

When I started learning JAVA, I was surprised that the printing of arrays is different. What I mean is, in order to print out the whole array full of float values, you can't just loop (i) times and do System.out.println("%.2f", array[i]);.

The way to print it is System.out.println(Arrays.toString(array));

If it wasn't an array, I would round up the float just with System.out.println("%.2f, val) . However, with an array, I don't know how to do it. Appreciate the help.

Here is my whole class for calculating. Every calculation is correct and well, the only problem is rounding and printing.

package sample;

import java.util.Arrays;

public class Calculations extends Data{

    public void calculateLinearCredit()
    {
        double[] linearCredit = new double[super.term];
        double[] linearInterest = new double [super.term];
        double[] linearPayment = new double [super.term];


        double firstMonthInterest = ((super.loan / super.term) * super.percentage) / 100;
        double Credit = super.loan / super.term;
        double interestDiff = firstMonthInterest/12;

        linearInterest[0] = firstMonthInterest;


        for(int i = 0; i < linearCredit.length; i++)
        {
            linearCredit[i] = Credit;
        }

        for(int i = 1; i < linearInterest.length; i++)
        {
            linearInterest[i] = linearInterest[i-1] - interestDiff;
        }


        for(int i = 0; i < linearPayment.length; i++)
        {
            linearPayment[i] = linearInterest[i] + linearCredit[i];
        }

        //-----------------------------------------------
        //System.out.println(Arrays.toString(linearPayment));
        //System.out.println(Arrays.toString(linearCredit));
        //System.out.println(Arrays.toString(linearInterest));
    }
}

Solution

  • Simply use Math.round()

    double[] array = new double[]{12.5698, 123.12345,0.1, 41234.212431324};    
        for (int i=0;i<array.length;i++) {
         array[i] = Math.round(array[i] * 100.0) / 100.0;
        System.out.println(array[i]);
    }
    

    in order to print out the whole array full of float values, you can't just loop (i) times and do System.out.println("%.2f", array[i]);

    You can but using System.out.format()

    for(int i=0;i<array.length;i++)
    {
        System.out.format("%.2f ",array[i]);
    
    }
    
    Output: 12.57 123.12 0.10 41234.21