原因
二进制与十进制转化时的精度丢失
现象
<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>
解决办法
采用tofixed方法取小数点后两位。随机数直接取整。
<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>