Need help converting a String to boolean in JavaScript

Hi there,

I’ve been using parseInt and parseFloat a bit while reading player pref strings back in to my scene, but I can’t seem to get the same thing to work with booleans.
I can’t seem to find the right function for that but I’m sure there must be something similar to the others, parseBool doesn’t work.
Anyone know what the function im looking for is? So far I’ve just worked around it by using integers of 0 to 1, but visually it’d be nicer to have the checkboxes :slight_smile:

Thanks
Pete

var bool : boolean = !(inputVar == 0)

You could write a parseBool function, too -

function parseBool( x ) : boolean {
  try {
    return !( 0 == x ); 
  } catch ( e ) {
    try { 
      return ("true" == x );
    } catch ( e ) {
    }
  }
  return false;
}

I think you might be able to replace the try/catches with some typeof calls, but I haven’t used that function enough to say for sure.

What’s wrong with using 1’s and 0’s ?

  var myInt : int = PlayerPrefs.GetInt("LoggedIn")
  var myBoolean : boolean = (myInt) ? true : false;

erm… it should be as simple as:

result=sString=="True";

it always returns false if it can’t recognize “True”

If you want, compare it against Boolean.TrueString/Boolean.FalseString, or even better, use the Boolean.Parse() method…

Hey guys,

I think I’ll be able to work it out from that. I just thought i was missing something really simple (and clean) like the rest of the ones I’m using.

I tried Boolean.Parse() but it ends up with this error -
Unknown identifier: ‘Boolean’.

Thanks
Pete

System.Boolean.Parse(). Or TryParse, in case the input string might not equal TrueString or FalseString. For reading/writing booleans in PlayerPrefs, use BoolPrefs.

–Eric

Hey Eric,
That’s more like what I was looking for!
BoolPrefs looks cool too, but I am reading a big string that has all kinds of types so I’ll stick with this for now.
Thanks Again!
Pete.