Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda