Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to convert an int to a boolean

Tags:

c#

int

boolean

The input int value only consist out of 1 or 0. I can solve the problem by writing a if else statement.

Isn't there a way to cast the int into a boolean?

like image 210
DeepSea Avatar asked Feb 27 '13 09:02

DeepSea


People also ask

How do you turn an int into a boolean?

To convert integer to boolean, firstly let us initialize an integer. int val = 100; Now we will declare a variable with primitive boolean. While declaration, we will initialize it with the val value comparing it with an integer using the == operator.

How do you convert int to boolean in Python?

Integers and floating point numbers can be converted to the boolean data type using Python's bool() function. An int, float or complex number set to zero returns False . An integer, float or complex number set to any other number, positive or negative, returns True .


2 Answers

int i = 0; bool b = Convert.ToBoolean(i); 
like image 163
Evelie Avatar answered Oct 21 '22 10:10

Evelie


I assume 0 means false (which is the case in a lot of programming languages). That means true is not 0 (some languages use -1 some others use 1; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:

bool boolValue = intValue != 0; 
like image 25
Corak Avatar answered Oct 21 '22 12:10

Corak