解决浮点数*100后精度问题

例子:

  1.11*100=111.00000000000001;

    signFigures: function(num, rank = 6) {
                if(!num) return(0);
                const sign = num / Math.abs(num);
                const number = num * sign;
                const temp = rank - 1 - Math.floor(Math.log10(number));
                let ans;
                if (temp > 0) {
                    ans = parseFloat(number.toFixed(temp));
                }
                else if (temp < 0) {
                    ans = Math.round(number / Math.pow(10, temp)) * temp;
                }
                else {
                    ans = Math.round(number);
                }
                return (ans * sign);
            },

使用:

this.signFigures(1.11*100)=111;

posted @ 2020-03-09 15:29  柠檬青味  阅读(1113)  评论(0编辑  收藏  举报