Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 579
Roman Rdgz Avatar asked Sep 22 '11 10:09

Roman Rdgz


People also ask

Can we declare array as float?

You have to specify the size if you are going to define array float in this way: float array[4]; You can define the array without the size.

Can a double be an array?

An array is a sequence of values; the values in the array are called elements. You can make an array of int s, double s, or any other type, but all the values in an array must have the same type.

Can we declare array as float in Java?

getFloat() is an inbuilt method of Array class in Java and is used to return the element present at the given index from the specified Array as Float. Parameters: This method accepts two mandatory parameters: array: The object array whose index is to be returned.

Can an array store both integer and float variables?

Now my answer was: yes, since you can declare an array of objects and store integers and floats in it.


2 Answers

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];
}
like image 157
Jon Skeet Avatar answered Sep 29 '22 11:09

Jon Skeet


With Kotlin you can try something like this:

 val doubleArray = arrayOf(2.0, 3.0, 5.0)
 val floatArray = doubleArray.map { it.toFloat() }.toFloatArray()

or

 val floatArray = arrayOf(2.0, 3.0, 5.0).map { it.toFloat() }.toFloatArray()
like image 45
Antonis Radz Avatar answered Sep 29 '22 11:09

Antonis Radz