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

Time:01-31

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)}
/>

CodePudding user response:

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

CodePudding user response:

You can use on your input:

    <input type='number' value={rate}  min={0} max={1} step={0.000001} 
  onChange={e => addRate(parseFloat(e.target.value)} >

set the step the way you want to. And for the NaN, try it:

if(typeof num == 'number' || isNaN(num))

let me know if it works!

CodePudding user response:

If you are planning to work with inputs and numbers, to save you from a lot of headache (especially when using mobile devices to prompt user for a proper input type), fix errors caused by . vs ,, save time on developing code and getting cleaner code thanks to using directives I suggest you to check out some alternatives. It's not mine but man do I use this alot. https://digit-only.firebaseapp.com/demo I highly suggest this. Floting numbers and inputs are a pain in the...

If you don't want "yet another package" then you can ofcourse just inspect the code the get some ideas: https://github.com/changhuixu/ngx-digit-only/blob/main/projects/uiowa/digit-only/src/lib/digit-only.directive.ts

  •  Tags:  
  • Related