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

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

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 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