OMA
OMA

Reputation: 3691

How to cast Strings "1" and "0" to true and false in AS3?

In AS3 when you try to cast a String containing "1" or "0" to Boolean using Boolean() the result is true in both cases.

Boolean("1") // true
Boolean("0") // true

How would you get true in the first case and false in the second case?

Upvotes: 0

Views: 589

Answers (2)

zzzzBov
zzzzBov

Reputation: 179046

How would you get true in the first case and false in the second case?

There are a variety of ways to convert '1' and '0' to true and false respectively, but it matters more how other numbers are cast for how to handle these cases.

For example, if you want to treat these strings as numbers, and cast them to boolean as though they were numbers, then you can just cast to Number before casting to Boolean:

var t = '1';
var f = '0';

Boolean(Number(t)); //true
!!+f; //false, terse syntax

This means that other non-zero numbers such as '-1' will become true, and non-numbers that convert to NaN, such as 'word' will become false.

If instead you want to detect if the value is '1' exactly, and everything else should be false, then use a simple equality comparison:

t === '1'; //true
f === '1'; //false

If instead you want to detect if the value is not zero, you can use a simple inequality comparison:

t !== '0'; //true
f !== '0'; //false

In the end what matters are your expected input and their respective expected output.

Upvotes: 1

OMA
OMA

Reputation: 3691

You could check for the string to contain the exact value for "1", like this:

var myBool:Boolean = (myString === "1");

Or you could do a double casting, like this:

var myBool:Boolean = Boolean(int(myString));

The latter has the advantage of being true for strings with whitespace (" 1") or even "01" (in case this is desirable), but still "0", " 0" or "00" would be false.

I've added this Q&A here because I just stumbled into this problem of Boolean("0") being true. If you have a better solution, feel free to comment.

Upvotes: 2

Related Questions