Skip to content
Advertisement

Allow input type number only a number/float between 0-1

I want to have an input number that allows any float between 0-1 including both whole numbers. But it’s proving quite tricky just getting the backspace to actually delete a numbers as it comes as NaN

I got this:

const [rate, setRate] = useState<number>(0)

const addRate = (num: number) => {
  if (typeof num !== 'number') {
    setRate(0)
  } else {
    setRate(num)
  }
}

...
<input
  type='number'
  value={rate}
  onChange={e => addRate(parseFloat(e.target.value)}
/>

Advertisement

Answer

You can use achieve your goal with adding some conditions to the addRate state, also using step prop of input element:

import { useState } from "react";

export default function App() {
  const [rate, setRate] = useState(0);

  const addRate = (num) => {
    if (typeof num !== "number" || isNaN(num) || num > 1) {
      setRate(0);
    } else {
      setRate(num);
    }
  };
  return (
    <input
      type="number"
       value={rate === 0 ? "" : rate}
      step={0.01}
      onChange={(e) => addRate(parseFloat(e.target.value))}
    />
  );
}

Edit vigorous-framework-x233g

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement