I have a function signature like:
static public double[][] G2Sweep(int row1, int row2, double[][] mtx)
{
mtx = (float) mtx;
}
But I need to covert the double[][] matrix into float values. How is this done as the code can't explicitly convert it?
Here double is a primitive data type its object can't be used to call the Float class method. If done so it will give the above error.
floatValue() to Convert Double to Float in Java. Another way to convert a double value into a float data type in Java is by using the wrapper class Double. This class wraps a primitive data type double in an object.
As float can have decimal values that don't have corresponding long value. Therefore, we'll receive the same error. The double values can be too large or too small for an int and decimal values will get lost in the conversion. Hence, it is a potential lossy conversion.
public static float[][] Convert(double[][] mtx)
{
var floatMtx = new float[mtx.Length][];
for (int i = 0; i < mtx.Length; i++)
{
floatMtx[i] = new float[mtx[i].Length];
for (int j = 0; j < mtx[i].Length; j++)
floatMtx[i][j] = (float)mtx[i][j];
}
return floatMtx;
}
Or:
public static float[][] Convert(double[][] mtx)
{
return mtx.Select(i => i.Select(j => (float)j).ToArray()).ToArray();
}
No, you can't convert double to float in place, especially for arrays. You need to create copy with correct type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With