Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert boolean result into number/integer

I have a variable that stores false or true, but I need 0 or 1 instead, respectively. How can I do this?

like image 506
hd. Avatar asked Oct 19 '11 11:10

hd.


People also ask

Can a Boolean value be converted to an integer value?

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”.

Can boolean be a number?

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.

How do you convert boolean to int in TypeScript?

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).

How do you change boolean to int in Python?

To convert boolean to integer in python, we will use int(bool) and then it will be converted to integer.


3 Answers

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.

like image 154
lonesomeday Avatar answered Oct 16 '22 06:10

lonesomeday


Javascript has a ternary operator you could use:

var i = result ? 1 : 0;
like image 20
Andy Rose Avatar answered Oct 16 '22 07:10

Andy Rose


Imho the best solution is:

fooBar | 0

This is used in asm.js to force integer type.

like image 147
kralyk Avatar answered Oct 16 '22 06:10

kralyk