I cannot add number together and despite using parseFloat I still get NaN.
This code;
console.log(freshsnow_single_resort.fs_ski_resort_aa_advanced_length);
console.log(freshsnow_single_resort.fs_ski_resort_aa_expert_length);
console.log(freshsnow_single_resort.fs_ski_resort_aa_freeride_length);
console.log(freshsnow_single_resort.fs_ski_resort_aa_extreme_length);
let fs_ski_resort_aa_advanced_length = parseFloat(freshsnow_single_resort.fs_ski_resort_aa_advanced_length)
let fs_ski_resort_aa_expert_length = parseFloat(freshsnow_single_resort.fs_ski_resort_aa_expert_length)
let fs_ski_resort_aa_freeride_length = parseFloat(freshsnow_single_resort.fs_ski_resort_aa_freeride_length)
let fs_ski_resort_aa_extreme_length = parseFloat(freshsnow_single_resort.fs_ski_resort_aa_extreme_length);
let expert_km = parseFloat(fs_ski_resort_aa_advanced_length + fs_ski_resort_aa_expert_length + fs_ski_resort_aa_freeride_length + fs_ski_resort_aa_extreme_length);
console.log(typeof fs_ski_resort_aa_advanced_length );
console.log(typeof fs_ski_resort_aa_expert_length );
console.log(typeof fs_ski_resort_aa_freeride_length );
console.log(typeof fs_ski_resort_aa_extreme_length );
console.log( expert_km );
Produces the below in the console:
4901.39
2057.49
0
<<blank/novalue
Number
Number
Number
Number
NaN
I cannot understand what is going on… any help much appreciated.
>Solution :
parseFloat is not a function that will always return a valid number for you. The returned type is always a number, however typeof NaN is still a number.
console.log(parseFloat("Invalid Number"));
console.log(typeof NaN);
console.log(typeof parseFloat("Invalid Number"));
console.log(NaN + 100);
You need an additional check and a fallback in case the result is NaN.
For instance if you want to treat them as zeros:
const value = "<<blank/novalue";
const parsedValue = parseFloat(value);
const safeParsedValue = isNaN(parsedValue) ? 0 : parsedValue;
console.log(safeParsedValue);
You might also want a check for too large values, since when the number is outside the double-precision 64-bit IEEE 754-2019 the function will return Infinity.
parseFloat("1.7976931348623159e+308"); // Infinity
parseFloat("-1.7976931348623159e+308"); // -Infinity