AS: ROUNDING
By Snubby
What will I learn?
You will learn everything to know there is to know about rounding, including...
- Simple rounding
- The Math class
- Different types of rounding
- Rounding to the nearest 1, 2, 3, 4, 5, 10, 20... etc.
- The uses of rounding.
And so on!
Pff, I already know how to round, thats noooooob...
Yeah hot shot but do you know how to round to the nearest ten? huh? I didn't think so...
BASIC:
What is rounding? Rounding is taking a decimal number and increasing it to the nearest whole number. example.
0.7 to 1.
Rounding comes in handy when you want to show a number without a bazillion decimal places after it, like a preloader percentage.
Here are the different forms of rounding...
Math.round();
Math.floor();
Math.ceil();
Each form takes one argument (something between brackets), the number you want to round.
Math.round(); // Round a number either up or down. from 0-4 rounds down, and 5-9 rounds up.
Math.floor(); // Round a number down.
Math.ceil(); // Round a number up.
Here is a line of code that includes rounding you might see in a script...
percentage = Math.round(getBytesTotal() / getBytesLoaded() * 100);
that could act as a preloader variable.
INTERMEDIATE
When using rounding, you can combo it with other Math, like random(). If you want to go to a random frame from 1 - 10, you can use rounding and random (because there is no frame 5.7, you have to go to frame 6).
gotoAndStop(Math.round(Math.random() * 9 + 1));
The random creates a random number from 0 - 1, like 0.943753. I then multiply that by 9, giving a number from 0-9. Then I add one, giving a number from 1-10.
ADVANCED? (to the nearest)
Say I want a number from one to ten. I was working on a pixel game engine where I wanted to have a charged up laser, that as you held the mouse the laser got bigger to the nearest 10 pixels. Wanna see?
Example
The Code // remember, its not API, I've got crap in the library
So how do me do it? Well we use a combination of rounding, dividing and multiplying. Heres my script for a number to the nearest 10.
var myNum:Number = 6.9384;
So, this creates a numerical variable, myNum, and sets it to 6.9384.
var myRoundNum:Number = Math.round(myNum / 10) * 10;
This takes myNum, and rounds it to the nearest 10. How?
Math.round(myNum / 10);
so this divides 6.9384 by ten, which is 0.69384 (but who cares?) and then rounds that, which makes one. That then is multiplied by ten, which gives 1 * 10 = 10!!
If I wanted to round to the nearest 5, i could go
var myRoundNum:Number = Math.round(myNum / 5) * 5;
see?
- - - - - - - - - -
I'm open to comments, though I think the rounding to the nearest is probably the only usefull part of this :P