Home > Software design >  Trying to cast string to number returns NaN
Trying to cast string to number returns NaN

Time:03-20

I'm confused... I have a number as a string ('3'), and I want it to become a normal Number-type number. If I go into any console and do Number('3'), it'll return 3.

However, in this code it returns NaN:

const attr = "rating='3'";
const [attrName, attrValue] = attr.split('=');
// if the attrValue is a number, cast it as such
if (!Number.isNaN(attrValue)) {
    const numAttr = Number(attrValue);
    console.log('num: ', numAttr, attrValue.length, attrValue.charCodeAt(0));
}

I confirm that the first char code of the number string is 39, which is single apostrophe, and its length is 3, so no sneaky hidden chars.. The numAttr value is NaN though. It also does go into the if statement, which presumably tells me that it can, in fact, become a number?

CodePudding user response:

You have to replace the single Quotes around the number. You can use the replace() function for this:

const attr = "rating='3'";
let [attrName, attrValue] = attr.split('=');
const para1 = attrName;
const para2 = attrValue.replace(/'/g, '');

console.log(para1, para2);
console.log('isNAN()?',isNaN(para2))

isNaN = is not a Number?

  • Related