Convert a double array to a float array Convert a double array to a float array arrays arrays

Convert a double array to a float array


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];}


Here is a function you could place in a library and use over and over again:

float[] toFloatArray(double[] arr) {  if (arr == null) return null;  int n = arr.length;  float[] ret = new float[n];  for (int i = 0; i < n; i++) {    ret[i] = (float)arr[i];  }  return ret;}


For future reference; this can also be done a bit more concisely by using Guava, like this:

double[] values = new double[]{1,2,3};float[] floatValues = Floats.toArray(Doubles.asList(values));