Question:
How to add number together and despite using parseFloat I still get NaN

Solution

You cannot rely on parseFloat to consistently provide you with a valid number. Although typeof NaN is still a number, the returned type is always a number.


console.log(parseFloat("Invalid Number"));

console.log(typeof NaN);

console.log(typeof parseFloat("Invalid Number"));


console.log(NaN + 100);


You require a backup plan and an extra check in case the outcome is NaN. If you wish to treat them as zeros, for example:


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


Suggested blogs:

>How to Select checkboxes on an HTML treeview with JavaScript?

>How to use querySelectorAll()" with multiple conditions in JavaScript?

>How to fix mouseover event glitch in JavaScript?

>How to do light and dark mode in a website using HTML and JavaScript?

>How to manipulate manipulating Array object in JavaScript?

>How to merge an object into Array with the same key in JavaScript?

>Javascript Error Solved: Property 'id' does not exist on type 'T'

>Why highlighted table row using class not working in JavaScript?

>How to rename an object key based on the condition in JavaScript?

>How to sort an array based on another array in Javascript?

>Javascript: Modal not closing with a button


Nisha Patel

Nisha Patel

Submit
0 Answers