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
?
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.
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 .
int i = 0; bool b = Convert.ToBoolean(i);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With