Search code examples
javaarraysfloating-pointdouble

Convert a double array to a float array


I have a double[][] array, and I want to get one row into a float[] array. Casting didn't worked at first, so I looked for something different.

I found here in stackoverflow an elegant solution to convert Object[] to String[], which also would work if I were converting Object[] to float[].

So: is there any elegant way of converting double[] to float[], or a double[] to Object[] so I can use the code at the other post?

I'll provide an example code of what I'm doing, even I think it's not neccesary:

double[][] datos = serie.toArray();
double[][] testArray = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}};
double[] doubleArray = Arrays.copyOf(testArray[1], testArray[1].length);
// This would be great but doesn't exist:
//float[] floatArray = Arrays.copyOf(doubleArray, doubleArray.length, float[].class);

Solution

  • No, casting the array won't work. You need to explicitly convert each item:

    float[] floatArray = new float[doubleArray.length];
    for (int i = 0 ; i < doubleArray.length; i++)
    {
        floatArray[i] = (float) doubleArray[i];
    }