[SOLVED] How to limit set the maximum decimal places of a number as 8 decimal places in React using javascript

Issue

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

Solution

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);
};
handleAmount(10.21231123124124124142);
handleAmount(7.242);
handleAmount(80.00000000000);
handleAmount(21.00000001);

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

Answered By – Arkin Solomon

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *