Page 1 of 1

Tip for rounding numbers

Posted: August 8th, 2006, 11:15 pm
by nab
Hi all,

we often have to round numbers in our scripts (or expressions). I usually use the Math.round() method to accomplish this, for example:

Code: Select all

x = 57.351245; 
alert(Math.round(x*100)/100); // 2-digit precision -> 57.35
Yesterday I've found an alternative way to round numbers with a defined precision: the to.Fixed() Javascript method. It's recognized by AE in scripts and expressions as well.
Example:

Code: Select all

pi = 3.14159;
alert(pi.toFixed(2)); // 2-digit precision -> 3.14
Of course setting the precision to 0, is equivalent to the Math.round() method. [position[0].toFixed(0),position[1].toFixed(0)]

I guess some of you already know this method but I don't remember to have seen it already in a script so ...

More rounding fun

Posted: November 5th, 2006, 4:15 am
by Darkmoon_UK
Related to this, I found a delightful method to remove the decimal places from a number, equivalent to Math.floor.

Simply 'bitwise OR' with '0':

( ( expression ) | 0 )

This is a useful alternative as when using it to find the whole number of a division, it works properly for negative numbers.

Posted: November 5th, 2006, 10:49 pm
by nab
nice !
There is also the shift operator ">>" to emulate Math.floor.

Code: Select all

x = 2.178;
alert(x >> 0); // return 2