js--Decimal calculation accuracy problem

the reason

Loss of precision when converting binary to decimal

phenomenon

 <script>
        console.log(99.99+0.02);
        console.log(33.122+44.1);
        for (var i = 0; i < 10; i++) {
    
    
            // toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。
            var num = Math.random().toFixed(2)*100;
            console.log(num);         
        }    
 </script>

Insert picture description here

Solution

Use tofixed method to take two decimal places. The random number is directly rounded.

   <script>
        console.log ((99.99+0.02).toFixed(2));
        console.log( (33.122+44.1).toFixed(2));
        for (var i = 0; i < 10; i++) {
    
    
            // toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。
            //向下取整
            var num =Math.floor(Math.random()*100);    
            console.log(num);         
        }
    </script>

Guess you like

Origin blog.csdn.net/weixin_42898315/article/details/112258090