Q:

Weird double printing in array

I'm writing a program that prints an array containing the sum of the values of two arrays passed as parameters. It all works fine with the exception of the last double value. I want the last value to print as 3.1. Instead it's printing the following:
[5.9, 11.7, 2.4, 3.0999999999999996]
Not sure how to format to print otherwise as I'm not allowed to use a String to solve it. I'm not having that problem with the other values. Here's my code and thanks for the help!
    import java.util.*;

class Sum
{
    public static void main (String [] args)
    {
        double [] a1 = {4.5, 2.8, 3.4, 0.8};
        double [] a2 = {1.4, 8.9, -1.0, 2.3};

        arraySum (a1, a2);

        System.out.println (Arrays.toString (arraySum (a1, a2)));   
    }

    public static double [] arraySum (double [] x, double [] y)
    {
        int length = 0;
        double [] sum = new double [x.length];
        length = x.length;

            for (int i = 0; i <= length - 1; i++)
            {
                sum[i] = x[i] + y[i];
            }

        return sum;

    }
}

A:

You want to use deciaml format      
DecimalFormat df=new DecimalFormat("#.#");
String outputString=df.format(sum);

A:

This is due to the IEEE floating point model. It can't represent exactly 3.1. To print it like you want, you will have to do it manually, instead of using Arrays.toString. Loop over the doubles and format them:
public static String toString(double[] x, DecimalFormat format)
{
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    for (int i = 0; i < x.length; ++i)
    {
        sb.append(format.format(x[i]));
        sb.append(", ");
    }
    sb.delete(sb.length() - 2, sb.length());
    sb.append("]");
    return sb.toString();
}

And then call like:
toString(sum, new DecimalFormat("#.#"));

To do the trick using only doubles, you might try to apply this, but this is dirty and not guaranteed to work:
double x = ...;
x = 0.001 * Math.round(x * 1000.0);
System.out.println(x);

