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

219
Visualizações
Javascript validate number commas and decimal

I want to return the number true if it is a valid number that contains only digits with properly placed decimals and commas, otherwise return the number false. For example: if number is 1,093,222.04 or 0.232567 then my program should return the number true, but if the input were 1,093,22.04 then my program should return the number false. For example:

input: 1,093,222.04 => true
input: 0.232567 => true
input: 1267 => true
input: 1,093,22.04 => FALSE
input: 1.282,04 => FALSE
input: abcd124 => FALSE

I tried this but 1,093,222.04 returns false. It should return true

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try using regex instead

const isNumber = x => !!`${x}`.match(/^\d*(,\d{3})*(\.\d*)?$/)

console.log(isNumber("1,093,222.04")) // true
console.log(isNumber("0.232567")) // true
console.log(isNumber("1267")) // true
console.log(isNumber("1,093,22.04")) // false
console.log(isNumber("1.282,04")) // false
console.log(isNumber("abcd124")) // false

Do note that the function must take in a string, since if you pass in the number itself, the commas , will split the "number" into different parameters

about 4 years ago · Juan Pablo Isaza Relatório

0

I first create a helper function to parse strings into a float. I use a regular expression to remove all characters that are not a period or digit, then I use parse float to turn it from a string into a float.

I have a function to compare test whether or not the string is properly formatted. I first convert the string to a float, then I format the float as the proper locale string. If the correctly formatted string and the string given are both the same, then I return true, otherwise I return false.

EDIT

I added some validation for long decimals, however this example is in no way meant to be a complete solution, just pointing you in the right direction. Depending on your use case you may need more validation or conditions for passing strings. i.e. this example will show .023 as invalid, because the locale string is properly 0.023. With this demo you should be able to add more validation as needed

const sToFloat = s => parseFloat(s.replace(/[^\d.]/g, ""));
function goodStringFormat(str) {
  let nOfDecimals = 0;
  if (str.includes(".")) nOfDecimals = str.split(".")[1].length;
  const float = sToFloat(str);
  const formatted = float.toLocaleString(undefined, {maximumFractionDigits: nOfDecimals});
  if (formatted === str) return true;
  return false;
}


console.log(`
  Testing 1,093,22.04
  good? ${goodStringFormat("1,093,22.04")}
  
  Testing 0.02123123123
  good? ${goodStringFormat("0.02123123123")}
  
  Testing 1,093,222.04
  good? ${goodStringFormat("1,093,222.04")}
  
  Testing 1231231,093,222.04
  good? ${goodStringFormat("1231231,093,222.04")}
  
`);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can try to remove the ',' and input.replaceAll(',','') and then do the validation, but you need to have your formatter function after all the check

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