Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!