13 February 2011

Actionscript 3: Better Random Function & Better Rounding Function

I was amazed at how lame the rounding and random functions are in AS3 so I've written 2 simple functions to add much needed functionality. Enjoy...

//Returns a random number between from and to inclusive
function randomNo(to:Number,from=0,decimalPlaces=0):Number{
 var ret=roundDecimal(Math.random()*(to-from)+from,decimalPlaces)
function roundDecimal(num:Number, precision:int):Number{
 var decimal:Number = Math.pow(10, precision);
 return Math.round(decimal* num) / decimal;
randomNo(2) //returns 0, 1 or 2
randomNo(20,18,2) //returns anything from 18.00 to 20.00

No comments:

Post a Comment

Cron Design Studio: Dublin based web design & software development