Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda