Search code examples
javaandroidarraysdecimal-point

Restricting decimal places in an array


Currently, the output of this array has a too large decimal place trail. How can I restrict this to say 2 decimal places? By this I mean the array 'percentage1'. I've seen methods to do it online, but I don't understand how I would implement those methods into the code as shown below.

int[] correct1 = {20, 20, 13, 15, 22, 18, 19, 21, 23, 25};
int[] incorrect1 = {2, 1, 5, 2, 2, 5, 8, 1, 0, 0};

    double[] percentage1 = new double[correct1.length];
    for(int a = 0; a < correct1.length; a++ ){ 
             percentage1[a] = (((double)correct1[a] / (correct1[a] + incorrect1[a]))*100);
        }

Any help would be very much appreciated. Thanks


Solution

  • Please try adding a DecimalFormat object.

    1. Add this to the beginning of the loop, it declares the format you're looking for - 2 decimal places: DecimalFormat df = new DecimalFormat("#.##");

    2. Format it using format, then convert it back into a double. The reason why you need to restore it back is that format returns a String.

      percentage1[a] = Double.valueOf(df.format((((double)correct1[a] / (correct1[a] + incorrect1[a]))*100)));

    See revised code below:

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] correct1 = {20, 20, 13, 15, 22, 18, 19, 21, 23, 25};
        int[] incorrect1 = {2, 1, 5, 2, 2, 5, 8, 1, 0, 0};
    
            double[] percentage1 = new double[correct1.length];
            DecimalFormat df = new DecimalFormat("#.##");
            for(int a = 0; a < correct1.length; a++ ){ 
                     percentage1[a] = Double.valueOf(df.format((((double)correct1[a] / (correct1[a] + incorrect1[a]))*100)));
                     System.out.println(percentage1[a]);
                }
    
    }
    

    Sample result:

    90.91
    95.24
    72.22
    88.24
    91.67
    78.26
    70.37
    95.45
    100.0
    100.0