lunes, 13 de agosto de 2018

[Java] Convert float[] to double[]

Typically when you have a float array in java, you cannot simply cast it to a double array like you do with other types.

here is a nice and simple function to convert a float array into a double array without loosing precision.


     public double[] floatToDouble(final float[] aFloatArray) {
         
        DoubleStream doubleStream = IntStream.range(0, aFloatArray.length)
                .mapToDouble(i -> aFloatArray[i]);
        
        return doubleStream.toArray();
     }

So in summary you could use it like this:


     public void aMethod(){
        final float[] aFloatArray = new float[]{
                1.02f,
                2.39f,
                13.0884f
        };
        
        final double[] aDoubleArray = floatToDouble(aFloatArray);
     }


And there it is! A simple and elegant way to convert your float arrays to double arrays.

No hay comentarios:

Publicar un comentario