F8as2
Background:
In trying to respond to a question I wrote a bit of code that just adds 0.01 to a number.?It is displayed in a dynamic text field.?If I start counting from 0 it only counts to 0.06.?The counting stops but the onEnterFrame keeps running.
The Code:
var num:Number = 0;
this.onEnterFrame = function() {
?num += .01;
?trace(num);
?num = Math.floor(num*100)/100;
?trace('' ''+num);
};
The Output:
0.01
?0.01
0.02
?0.02
0.03
?0.03
0.04
?0.04
0.05
?0.05
0.06
?0.06
0.07
?0.06
0.07
0.06
repeats 0.07
?0.06
The Question:
Why did the code stop incrementing after 0.07??
Thanks,
F8as2 - Headscratcher! +=...It seems to have something to do with your line that is performing the Math.floor function on the calculation. When I comment that line out the increment works as expected. If I change it to Math.ceil it works as expected. However if you code it like this with Math.floor
var num:Number = 0;
this.onEnterFrame = function()
{
?num += .01;
?trace(''before floor:'' + num);
?num = num*100;
?trace(''after multiply:'' + num);
?Math.floor(num);
?num = num/100;
?trace(''after floor:'' + num);
?
}
It works as expected. Apparently there is something sneaky going on in the call to Math.foor(num*100) that proper mathematics does not like. It's interesting because I am sure I have done this in code before, but maybe I haven't.
Anyway just perform the floor command on a number after you have the final number you need floored.
F8as2 - Headscratcher! +=...It may just be a case of the imprecision in calculation, which isn't abnormal in Flash.?Sometimes you need to round values to get better results...
num = Math.floor(Math.round(num*100))/100;
Thank you MaxManNH?and Ned Murphy .
Problem solved.?If I didn't use Math.floor I did get .0699999999999999 instead of .07.
Thanks for the quick responses.
No comments:
Post a Comment