在Javascript中,如果数字超过8位,如何将其四舍五入到8位

How to round a number down to 8 decimal places if its over 8 decimal places in Javascript

本文关键字:8位 四舍五入 Javascript 如果 数字      更新时间:2023-09-26

我正在检查输入的数字是否超过了8位小数,如果超过了,我想将其四舍五入到8位小数。然而,当我输入数字1.234001时,它会自动将其四舍五入到小数点后8位。(1.234001/000000001)%1=0,所以我不知道它为什么四舍五入。这是我的代码

var SAT = 0.00000001;
if(!isNaN(input.value) && ((input.value / SAT) % 1 != 0)) {
                input.value = parseFloat(input.value).toFixed(8);
                console.log(6);
            }

用这种方式试试:

function nrOfDecimals(number) {
    var match = (''+number).match(/(?:'.('d+))?(?:[eE]([+-]?'d+))?$/);
    if (!match) { return 0; }
    var decimals =  Math.max(0,
       (match[1] ? match[1].length : 0)
       // Correct the notation.
       - (match[2] ? +match[2] : 0));
     if(decimals > 8){
        //if decimal are more then 8
        number = parseFloat(number).toFixed(8);
     }
     //else no adjustment is needed
     return number;
}