Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
Trying to cast string to number returns NaN

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!