Home > Software design >  How to limit set the maximum decimal places of a number as 8 decimal places in React using javascrip
How to limit set the maximum decimal places of a number as 8 decimal places in React using javascrip

Time:03-11

Im taking user input and trying to set the maximum amount of decimal places to 8 digits after decimal. I was researching this and I have seen solutions that tell me to do the javascript's .toFixed() method. However, I tried it and found that it will automatically tack on about 8 zeros into the input for whatever I input into the input field. For example if I type in 5 into the field, I would get the following in the input field: 5.00000000

This is not the goal, as I just want to limit the amount of decimal places a user can input to 8. It is fine if it is less than that.

Please see my code below. Thanks!

  const handleAmount = (value) => {
    const numberAmount = Number(value).toFixed(8);
    setAmount(numberAmount);
  };

          <TextField
              className={classes.textField}
              type="number"
              onChange={e => handleAmount(e.target.value)}
              value={amount}
              placeholder="0.000"
              inputProps={{
                maxLength: 8,
                step: '.01'
              }}
              variant="outlined" />

CodePudding user response:

You could do a little trick where you multiply the number by 1e8 and then round it, then divide by 1e8.

For example:

const setAmount = console.log;
const handleAmount = (value) => {
  const numberAmount = Number(value);
  const rounded = Math.round(numberAmount * 1e8) / 1e8;
  setAmount(rounded);
};
console.log(handleAmount(10.21231123124124124142));
console.log(handleAmount(7.242));
console.log(handleAmount(80.00000000000));
console.log(handleAmount(21.00000001));

However, the downside is that 41.000000000 for example would be parsed as 41.

  • Related