Az Expattech az ünnepek alatt (dec.24-jan.1.) zárva tart. Nyitás: 2024.január 2

ExpatTech Techblog

Peter Todd 2009.09.23. 10:10

Flash Cookbook - Appendix - universal rounding

This part is about a really useful function we make. Let's imagine a function what is rounding numbers. BUT! insteand of writing a rounder for each object type, we create a universal function. This will work with: number, movieclip, point and array. Obviously it will round the coordinates of the movieclip, and not its graphics. The elements of the array will be rounded, not the length of it.

Flash itself can't change the value of a Number (and neither of int, uint, boolean, string) globally what was passed to a function as a parameter, only locally. Therefore for the number type we have to return a value.

function round(obj:*, digit:int = 0):*
{
    var power:int = Math.pow(10, digit);
   
    if(obj is Array)
    {
        for(var i:int = 0; i < obj.length; i++) obj[i] = int(Math.round(obj[i] * power)) / power;
    }
   
    if(obj is Number)
    {
        obj = new Number(int(Math.round(obj * power)) / power);
        return obj;
    }
   
    if(obj is MovieClip)
    {
        obj.x = int(Math.round(obj.x * power)) / power, obj.y = int(Math.round(obj.y * power)) / power;
    }
   
    if(obj is Point)
    {
        obj.x = int(Math.round(obj.x * power)) / power, obj.y = int(Math.round(obj.y * power)) / power;
    }
}

 

usage:

var a1:Array = [66.60123, 49.85221];

trace(a1);
round(a1, 3);
trace(a1);

output:

66.60123,49.85221
66.601,49.852

and

var n1:Number = 98.65465464;

trace(n1);
n1 = round(n1, 3);
trace(n1);

output:

98.65465464
98.655