AS3 Random Boolean

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()) );


Or you can use the short hand if conditional statement, called the Ternary operation.

var randomBoolean:Boolean = (Math.random() > .5) ? true : false;


2 Responses to “AS3 Random Boolean”

  1. Just what I needed — thanks!

  2. Just call: var randomBoolean:Boolean = (Math.random() > .5)
    That will be enough

Leave a Reply