I have a variable that stores false
or true
, but I need 0
or 1
instead, respectively. How can I do this?
To convert boolean to integer, let us first declare a variable of boolean primitive. boolean bool = true; Now, to convert it to integer, let us now take an integer variable and return a value “1” for “true” and “0” for “false”.
A Boolean number has value True/ON and False/OFF; therefore, when a Boolean is converted into a number it would return 1 or 0 for True/ON or False/OFF respectively.
Use the Number object to convert a boolean to a number in TypeScript, e.g. const num = Number(true) . When used as a function, Number(value) converts a value to a number. If the value cannot be converted, it returns NaN (not a number).
To convert boolean to integer in python, we will use int(bool) and then it will be converted to integer.
Use the unary +
operator, which converts its operand into a number.
+ true; // 1
+ false; // 0
Note, of course, that you should still sanitise the data on the server side, because a user can send any data to your sever, no matter what the client-side code says.
Javascript has a ternary operator you could use:
var i = result ? 1 : 0;
Imho the best solution is:
fooBar | 0
This is used in asm.js to force integer type.
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