简体   繁体   中英

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM