AS3 Random Boolean
Posted by robert | Filed under ActionScript 3
Recently I built any application that needed a random Boolean. I used Math.random() which will give you a decimal number between 0 and 1. I then wrapped that with Math.round(), if the number is greater than .5 then the number will be 1 and everything else will be 0.
In ActionScript 3 and probably previous versions, 0 = false and 1 = true. You can do a simple test like trace(0 == false);. This nothing special but it might help someone.
function randomBoolean():Boolean { return Boolean( Math.round(Math.random()) ); } trace(randomBoolean());
Or you can use the short hand if conditional statement, called the Ternary operation.
var randomBoolean:Boolean = (Math.random() > .5) ? true : false; trace(randomBoolean);
October 29, 2011 at 9:49 am
Just what I needed — thanks!
December 25, 2015 at 2:01 pm
Just call: var randomBoolean:Boolean = (Math.random() > .5)
That will be enough