js looping numbers accumulate decimals

   let a = 0
    for (let i = 0; i < 30; i++) {
    
    
      a += 0.6
      console.log(a)
    }
  • print result
    insert image description here
  • Check it out and find that this is a bug in javascript floating point arithmetic.
  • The number of solutions * 1000 and finally divided by 1000
  • To solve the problem of js accumulating all the time, there will be a decimal bug. Multiply all numbers by 1000: num*1000; then accumulate to get sum, and then divide by 1000: sum=sum/1000;

Guess you like

Origin blog.csdn.net/weixin_43794749/article/details/121677925