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

165
Vistas
What is the best way to handle numbers with - and . with a controlled input?

I want to save the input in number type every time the value updates. However, with this approach, The value is stuck in NaN or 0 in the scenarios below.

scenario 1: changing 0 to 0.1 (stuck in 0 when '0.' left)

scenario 2: changing -15 to 1 (stuck in NaN when only '-' left)

What would be the best way to handle these cases when 1) the input has to be controlled element and 2) storing value in string format is not an option?

export default function App() {
  const [input, setInput] = useState(0)

  return (
    <div className="App">
     <input value={input} onChange={(e)=>setInput(parseFloat(e.target.value))}/>
    </div>
  );
}
about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

You can add a check before setting the state to see if the input value is parsable to a float.

function checkSetInput(e) {

  const val = parseFloat(e.target.value);

  if (isNaN(val)) 
    return // do not set state when the input is not parsable

  setInput(val); // otherwise do set the state

}

...

<input value={input} onChange={checkSetInput} />
about 4 years ago · Santiago Gelvez 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