SolutionCottage.com
Posted  24 Feb 2009 - 11:58:45

Category: JavaScript


Convert a boolean to integer in javascript

Issue:
You have a boolean and wish to convert this to an interger value in JavaScript.

Solution:

function convertBoolToInt()
{
var testBool = true;
result = (testBool)?1:0;
alert(result);
}



Marked as helpful by 72 users




5 comments:

10/15/2013 4:54:41 PM  Ben  wrote:

this is useful if you want custom values for true/false and not 1 and 0. also I don't trust that all javascript interpreters will do implicitly cast the same way. I prefer explicit casting in general


5/22/2013 5:46:39 PM  Warren Gaebel, B.A., B.C.S.  wrote:

Why so complicated? Just use the boolean where the context requires an integer. It converts automatically. Example: (true+true+true+false+true)/ (true-false+true) evaluates to 2. A boolean true behaves like the integer 1 and a boolean false behaves like the integer 0, AND VICE VERSA. There is no need for an explicit conversion.


8/31/2011 2:44:37 PM  i-meta.ru  wrote:

Do not create unnecessary function, use an explicit expression!


10/21/2009 5:43:36 PM  karaca  wrote:

var x = +false; //prints 0 var x = +true; //prints 1


8/3/2009 5:38:54 PM  didine  wrote:

right simply









© SolutionCottage 2008-2011 7/21/2017 3:31:43 AM