Hello i need to replace the Nan values with 0 in my array in java, any help thanks. you can find the example of my array.
The array type is double
and the contents of array are as follows.
x = [ 1 , 2, Nan , 4, Nan ]
Hello i need to replace the Nan values with 0 in my array in java, any help thanks. you can find the example of my array.
The array type is double
and the contents of array are as follows.
x = [ 1 , 2, Nan , 4, Nan ]
Loop the array and use isNaN
method from Double
to check if the number is NaN
.
for(int i=0; i<array.length; i++){
if(Double.isNaN(array[i])) {
array[i] = 0d;
}
}
In Java Nan != Nan evaluates to true.
double[] x = { 1 , 2, Double.NaN , 4, Double.NaN};
System.out.println(Arrays.toString(x));
for (int i = 0; i < x.length; i++) {
if(x[i]!=x[i]) {
x[i] = 0;
}
}
System.out.println(Arrays.toString(x));
Output:
[1.0, 2.0, NaN, 4.0, NaN]
[1.0, 2.0, 0.0, 4.0, 0.0]