简体   繁体   English

如何使用 javascript 在 React 中将数字的最大小数位设置为 8 位小数

[英]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.我接受用户输入并尝试将最大小数位数设置为小数点后 8 位。 I was researching this and I have seen solutions that tell me to do the javascript's.toFixed() method.我正在研究这个,我看到了告诉我执行 javascript's.toFixed() 方法的解决方案。 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.但是,我尝试了一下,发现无论我在输入字段中输入什么,它都会自动将大约 8 个零添加到输入中。 For example if I type in 5 into the field, I would get the following in the input field: 5.00000000例如,如果我在字段中输入 5,我会在输入字段中得到以下内容: 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.这不是目标,因为我只是想将用户可以输入的小数位数限制为 8。如果小于 8 位就可以了。

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 .你可以做一个小技巧,将数字乘以1e8然后四舍五入,然后除以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 .但是,缺点是例如41.000000000将被解析为41

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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