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

192
Visualizações
Check if a string with comma and period is a proper decimal number Javascript and extract numeric value

I am trying to validate my input field by checking if a string is a proper number with comma and period and if yes get the value

I tried two functions both not working as expected:

function isNumeric(str) {
    console.log(parseFloat(str.replace(/,/g,'')))  
    return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
           !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
  }


  const isValidNumber = (str) => {
      console.log(parseFloat(str.replace(/,/g,'')))
    //   return /^[0-9,.]*$/.test(str);
      return /^\d{0,4}(?:[.,]\d{1,3})?$/.test(str)
    //   return /^[0-9,]?.[0-9]/.test(str);
    // return /([0-9,.]+)$/.test(str)
  }

the test cases I prepared

console.log(isNumeric("2"))//true
console.log(isNumeric("2,00,000"))//true
console.log(isNumeric("2,7,5,.34"))//false
console.log(isNumeric("2,450,0000.22.22"))//false
console.log(isNumeric("2q,3,4"))//false

But it's not working as intended, I need a regex to fix this. Also need to check if parseFloat(str.replace(/,/g,'')) is the right way to extract value

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here is a general regex pattern for matching a number with proper thousands separator and an optional decimal component:

\d{1,3}(?:,\d{3})*(?:\.\d+)?

function isNumeric(input) {
    return /^\d{1,3}(?:,\d{3})*(?:\.\d+)?$/.test(input);
}

console.log(isNumeric("2"));                 // true
console.log(isNumeric("2,000,000"));         // true
console.log(isNumeric("3.14159"));           // true
console.log(isNumeric("2,7,5,.34"));         // false
console.log(isNumeric("2,450,0000.22.22"));  // false
console.log(isNumeric("2q,3,4"));            // false

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