1

Possible Duplicate:
Is JavaScript's Math broken?

I'm having some problems with my loop acting funny, here it is:

var duration = 1000;  /* 1000 millisecond fade = 1 sec */
var steps = 20;       /* number of opacity intervals   */
var delay = 5000;     /* 5 sec delay before fading out */

function fadeOut(eid) {
  for (i = 0; i <= 1; i += (1 / steps)) {
    setTimeout("setOpacity(" + (1 - i) + ",'"+eid+"')", i * duration);
    console.log("i="+i);
  }

}

and I used console.log to check out what's happening on the loop, and it turns out very weird:

i=0
i=0.05
i=0.1
i=0.15000000000000002
i=0.2
i=0.25
i=0.3
i=0.35
i=0.39999999999999997
i=0.44999999999999996
i=0.49999999999999994
i=0.5499999999999999
i=0.6
i=0.65
i=0.7000000000000001
i=0.7500000000000001
i=0.8000000000000002
i=0.8500000000000002
i=0.9000000000000002
i=0.9500000000000003
4

1 回答 1

2

这些是实际的浮点值。您可能希望将它们四舍五入以进行显示。

console.log("i="+i.toFixed(2));

http://www.mredkj.com/javascript/nfbasic2.html

于 2012-06-19T13:01:26.743 回答