Tip for rounding numbers

Find out why the . goes before the /

Moderator: Paul Tuersley

Post Reply
nab
Posts: 203
Joined: November 29th, 2005, 3:00 am
Location: Royan
Contact:

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 ...
Darkmoon_UK
Posts: 62
Joined: September 5th, 2006, 3:45 am
Location: Chiswick, London, UK
Contact:

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.
nab
Posts: 203
Joined: November 29th, 2005, 3:00 am
Location: Royan
Contact:

nice !
There is also the shift operator ">>" to emulate Math.floor.

Code: Select all

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