ChatGPT解决这个技术问题 Extra ChatGPT

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?

Here's a performance comparison of some of the provided techniques: jsperf.com/conversion-from-boolean-to-number.
Node.JS users will want to use bool === true ? 1 : 0, as it is by far the fastest in V8.
or just bool ? 1 : 0;

l
lonesomeday

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.


Albeit cool (I had never thought of this), it is incredibly slow (97% slower in Chrome, to be exact). Be wary!
Check out this revision. Number() is even slower.
It appears bool === true ? 1 : 0 is the fastest, with a close second from bool | 0.
Multiplying (e.g. 3*false) feels so wrong, but it works. :) Thanks!
@DerkJanSpeelman The fact that something is not allowed in Typescript does not mean that you shouldn't do it in Javascript. They are different (albeit related) languages.
A
Andy Rose

Javascript has a ternary operator you could use:

var i = result ? 1 : 0;

Best answer. Why? This works on truthiness which is more general and accepts any type (string, number, etcetera.) The unary answer is clever indeed, but if I pass it a string it returns NaN. So if you want L33T and guarantee the input, go urary, otherwise methinks the ternary + truthy test is best.
This solution is basically minimizing an if statement using the ternary operator.
The ternary solution is one of the fastest ways. Other solutions like +true or Number(true) are extremely slow. See benchmark.
@Dominik That benchmarking tool is extremely confusing and misleading. jsbench.me is a much better alternative.
k
kralyk

Imho the best solution is:

fooBar | 0

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


One of the fastest; +1.
Nice one. Also you could use "Boolean ^ 0". OR or XOR works.
This won't return a 1 integer will it if fooBar is not?
@ESR it casts everything to a number but not always the number you want, if you're dealing with other truthy types. 1 | 0 = 1; 0 | 0 = 0; true | 0 = 1; false | 0 = 0; 'foo' | 0 = 0; undefined | 0 = 0
Typescript error: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
R
Roko C. Buljan

I prefer to use the Number function. It takes an object and converts it to a number.

Example:

var myFalseBool = false;
var myTrueBool = true;

var myFalseInt = Number(myFalseBool);
console.log(myFalseInt === 0);

var myTrueInt = Number(myTrueBool);
console.log(myTrueInt === 1);

You can test it in a jsFiddle.


This is the best answer by far. At the bottom of course. Only "it takes an object" isn't right.
Link to mdn is much better than w3schools(eeek !): developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
I think this is the best way because it's easy to read and intention-revealing.
It is also the slowest.
Nice, that's exactly what I would do. Instead of using a ternary expression.
P
Philip

The typed way to do this would be:

Number(true) // 1
Number(false) // 0

Finally some decent answer. Thanks.
The ternary solution is one of the fastest ways. Other solutions like +true or Number(true) are extremely slow. See benchmark.
G
Gal Talmor

I created a JSperf comparison of all suggested answers.

TL;DR - the best option for all current browsers is:

val | 0;

.

Update:

It seems like these days they are all pretty identical, except that the Number() function is the slowest, while the best being val === true ? 1 : 0;.


Interestingly, the ternary is now fastest in Chrome 64.0.3282 on macOS 10.13.3.
That would be the fastest option, at the time. That is distinct from it being the best option.
t
tonyjcamp

I just came across this shortcut today.

~~(true)

~~(false)

People much smarter than I can explain:

http://james.padolsey.com/javascript/double-bitwise-not/


Interesting. I learned something new today. I won't use this technique in any project, though, because its potential to confuse future-me or teammates.
hacky js is my fav. seriously, +1
G
Gordon

When JavaScript is expecting a number value but receives a boolean instead it converts that boolean into a number: true and false convert into 1 and 0 respectively. So you can take advantage of this;

var t = true; var f = false; console.log(t*1); // t*1 === 1 console.log(f*1); // f*1 === 0 console.log(+t); // 0+t === 1 or shortened to +t === 1 console.log(+f); //0+f === 0 or shortened to +f === 0

Further reading Type Conversions Chapter 3.8 of The Definitive Guide to Javascript.


T
Teodor Maxim

TL;DR: Avoid Number constructor and +bool; use a simple if by default; resort to bool | 0, 1 * bool if benchmarks in your project do better this way.

This is quite an old question, and there exist many valid answers. Something I've noticed is that all benchmarks here are irrelevant - none take into account branch prediction. Also, nowadays, JS engines don't simply interpret the code, they JIT compile it to native machine code and optimize it prior to execution. This means that, besides branch prediction, the compiler can even substitute expressions with their final value.

Now, how do these 2 factors affect the performance of, well, boolean to integer conversion? Let's find out! Before we get into the benchmarks, it is important to know what we benchmark. For the conversion, we're using the following seven conversion methods:

Number constructor: Number(bool)

If statement (ternary used): bool ? 1 : 0

Unary operator +: +bool

Bitwise OR: bool | 0

Bitwise AND: bool & 1

Bitwise double NOT: ~~bool

Number multiplication: bool * 1

"Conversion" means converting false to 0 and true to 11. Each conversion method is ran 100000 times, measuring operations/millisecond. In the following tables, conversion methods will be grouped to their results accordingly. The percentage after the result represents how slow this method is compared to the fastest, in the same browser. If there is no percentage, the method is either the fastest or the difference is negligible (<0.01%). Benchmarks are run on a Macbook Pro 16-inch machine, with the Apple M1 Pro 10-core CPU and 16GB of RAM. Browsers are Chrome 102, Firefox 101 and Safari 15.5.

The first benchmark converts the constant true:

Method Chrome (V8) Firefox (Spidermonkey) Safari (Webkit) Number(bool) 31745.89 392.35 - 91.48% 31231.79 bool ? 1 : 0 31592.8 - 0.48% 4602.64 27533.47 - 11.84% +bool 31332.57 - 1.3% 4463.41 - 3.02% 27378.7 - 12.34% bool | 0 31488.5 - 0.81% 4441.4 - 3.5% 27222 - 12.84% bool & 1 31383.17 - 1.14% 4459.64 - 3.11% 27317.41 - 12.53% ~~bool 31265.85 - 1.51% 4442.35 - 3.48% 27434.72 - 12.16% bool * 1 31374.4 - 1.17% 4444.05 - 3.45% 27381.19 - 12.33%

Interesting! V8 shows some huge numbers, all of them approximately the same! Spidermonkey doesn't really shine, but we can see that the bitwise and multiplication tricks come first, and the ternary if second. Finally, Webkit's Number does similarly to V8's and the other methods fall behind, but are all close to each other. What are the takeaways? Browsers mostly manage to replace our conversions with simply the value 1. This optimization will take place where we can mentally replace the boolean to a constant value. The Number constructor is an intriguing anomaly - it severly falls behind in Firefox (91% slower!), while in Safari it is the fastest!

That above isn't a situation we'll ever encounter in real projects. So let's change our variables: the bool is now Math.random() < 0.5. This yields a 50% chance of true, 50% of false. Do our results change? Let's run this benchmark to see.

Method Chrome (V8) Firefox (Spidermonkey) Safari (Webkit) Number(bool) 1648.83 - 2.26% 280.34 - 86.4% 8014.69 bool ? 1 : 0 804.27 - 52.32% 731.57 - 64.5% 1294.02 - 83.85% +bool 1670.79 - 0.95% 2057.94 7753.99 - 3.25% bool | 0 1668.22 - 1.11% 2054.17 7764.81 - 3.12% bool & 1 1675.52 - 0.67% 2056.76 7193.08 - 10.25% ~~bool 1676.24 - 0.63% 2056.18 7669.48 - 4.31% bool * 1 1686.88 2060.88 7751.48 - 3.28%

The results are more consistent now. We see similar numbers for ternary if, bitwise, and multiplication methods across browsers, and the Number constructor again performs the worst on Firefox. Ternary falls behind, as it generates branches. Safari seems to be our top performer overall, each method yielding blazing fast results!

Let's see now how branch prediction affects our results with the following benchmark, where we change our boolean variable to Math.random() < 0.01, which means 1% true, 99% false.

Method Chrome (V8) Firefox (Spidermonkey) Safari (Webkit) Number(bool) 1643.13 - 1.68% 280.06 - 86.4% 8071.65 bool ? 1 : 0 1590.55 - 4.83% 1970.66 - 4.32% 7119.59 - 11.8% +bool 1662.09 - 0.55% 2054.09 7762.03 - 3.84% bool | 0 1669.35 2051.85 7743.95 - 4.06% bool & 1 1661.09 - 0.61% 2057.62 7454.45 - 7.65% ~~bool 1662.94 - 0.5% 2059.65 7739.4 - 4.12% bool * 1 1671.28 2048.21 7787.38 - 3.52%

Unexpected? Expected? I'd say the latter, because in this case branch prediction was successful in almost all cases, given the smaller difference between the ternary if and bitwise hacks. All other results are the same, not much else to say here. I'll still point out the horrific performance of Number in Firefox - why?

This endeavour brings us back to the original question: how to convert bool to int in Javascript? Here are my suggestions:

Use if statements, in general. Don't get smart - the browser will do better, usually, and usually means most of the situations. They are the most readable and clear out of all the methods here. While we're at readability, maybe use if (bool) instead of that ugly ternary! I wish Javascript had what Rust or Python have...

Use the rest when it's truly necessary. Maybe benchmarks in your project perform sub-standard, and you found that a nasty if causes bad performance - if that's the case, feel free to get into branchless programming! But don't go too deep in that rabbit hole, nobody will benefit from things like -1 * (a < b) + 1 * (a > b), believe me.

And some specifics:

Avoid Number(bool). While it is true that the Chromium platform (Chrome + Edge) has about 68% market share globally, Safari 19% and Firefox a mere 3.6%, there are enough other fast-performing methods that won't fully sacrifice a percentage of your users. Firefox has 7% desktop market share, which amounts to a sizable number of 173 million users.

In older benchmarks, +bool performed similarly bad to Number in Firefox, maybe take this in consideration, too - bitwise hacks and multiplication give consistently performant results across all browsers, in all situations. bool | 0 has the best chance to be familiar to other developers.

I will be forever grateful to you for reading until the end - this is my first longer, significant StackOverflow answer and it means the world to me if it's been helpful and insightful. If you find any errors, feel free to correct me!

EDIT: The previous benchmarking tool provided vague results, without an unit of measure. I've changed it, and also added benchmarks for Safari, which have influenced the conclusions.

Defined the conversion because it's not truly clear what boolean to integer means. For example, Go does not support this conversion at all.


upvoted for the effort but I can't think of a real use case when performance of such operation would matter :)
@skwisgaar Completely agree, although I think this operation is mostly thought of using when people feel the need to optimize
Excellent post, but am trying to figure out the interpretation of the benchmark numbers, as you indicate 'operations/second'. In the V8 browser debugger of my 5yr old Acer laptop, the following million operations run in 36ms(!): start=performance.now(); for (let i = 0; i < 1000000; i++) {let x = +(Math.random()<0.5);} end=performance.now(); console.log(end-start). What am I misinterpreting?
Thanks for your reply! Running the benchmarks myself, the numbers look more like operations/_millisecond_. Although in both Chrome's and Firefox's DevTools the same benchmarks seem to run faster on my machine too - maybe JSBench is a bottleneck. I'll change the measure unit for now, but this must be looked further into.
@TeodorMaxim just saw that you had replied... Sounds like it's not clear what JSBench is reporting... You might be best to create your own mini benchmark tool, as at least you'll know exactly what's being measured in addition knowing exactly how to interpret the results.
x
xanatos

The unary + operator will take care of this:

var test = true;
// +test === 1
test = false;
// +test === 0

You'll naturally want to sanity-check this on the server before storing it, so that might be a more sensible place to do this anyway, though.


I have changed the comments to ===, because true == 1 is true even withou the "explicit conversion :-) true === 1 instead is false.
N
Nicholas R. Grant

I was just dealing with this issue in some code I was writing. My solution was to use a bitwise and.

var j = bool & 1;

A quicker way to deal with a constant problem would be to create a function. It's more readable by other people, better for understanding at the maintenance stage, and gets rid of the potential for writing something wrong.

function toInt( val ) {
    return val & 1;
}

var j = toInt(bool);

Edit - September 10th, 2014

No conversion using a ternary operator with the identical to operator is faster in Chrome for some reason. Makes no sense as to why it's faster, but I suppose it's some sort of low level optimization that makes sense somewhere along the way.

var j = boolValue === true ? 1 : 0;

Test for yourself: http://jsperf.com/boolean-int-conversion/2

In FireFox and Internet Explorer, using the version I posted is faster generally.

Edit - July 14th, 2017

Okay, I'm not going to tell you which one you should or shouldn't use. Every freaking browser has been going up and down in how fast they can do the operation with each method. Chrome at one point actually had the bitwise & version doing better than the others, but then it suddenly was much worse. I don't know what they're doing, so I'm just going to leave it at who cares. There's rarely any reason to care about how fast an operation like this is done. Even on mobile it's a nothing operation.

Also, here's a newer method for adding a 'toInt' prototype that cannot be overwritten.

Object.defineProperty(Boolean.prototype, "toInt", { value: function()
{
    return this & 1;
}});

I've had two downvotes for this post. Why don't you explain why you downvoted it. Otherwise it's just a downvote without justification.
99 times the results of jsperf just lead you up the premature optimisation path, optimising nanoseconds off a loop when you should be focussed on that ugly SQL statement instead. thanks for providing a few different ways to approach this
What SQL statement? There's not a single query here. If you're referring to JSPerf, I was linking that from someone else's test. It's not my own. I honestly don't care about the performance aspect of this since it's a nothing operation. I created my own language that was nearly functionality identical to JS and I remember that casting to int was a stupidly fast operation. Climbing prototype chains was not. Which is why I'd still recommend the first way I did it, with a simple function that can be inlined by the compiler.
the SQL thing 'twas a generalisation. thanks for the insight
R
REMqb

You can also add 0, use shift operators or xor:

val + 0;
val ^ 0;
val >> 0;
val >>> 0;
val << 0;

These have similar speeds as those from the others answers.


J
Jose Velasco

In my context, React Native where I am getting opacity value from boolean, the easiest way: Use unary + operator.

+ true; // 1
+ false; // 0

This converts the boolean into number;

style={ opacity: +!isFirstStep() }

s
silkfire

+!! allows you to apply this on a variable even when it's undefined:

+!!undefined    // 0
+!!false        // 0
+!!true         // 1

+!!(<boolean expression>)  // 1 if it evaluates to true, 0 otherwise

D
DroidOS

You could do this by simply extending the boolean prototype

Boolean.prototype.intval = function(){return ~~this}

It is not too easy to understand what is going on there so an alternate version would be

Boolean.prototype.intval = function(){return (this == true)?1:0}

having done which you can do stuff like

document.write(true.intval());

When I use booleans to store conditions I often convert them to bitfields in which case I end up using an extended version of the prototype function

Boolean.prototype.intval = function(places)
{
 places = ('undefined' == typeof(places))?0:places; 
 return (~~this) << places
}

with which you can do

document.write(true.intval(2))

which produces 4 as its output.


E
Esger
let integerVariable = booleanVariable * 1;

K
Kamil Kiełczewski

try

val*1

let t=true; let f=false; console.log(t*1); console.log(f*1)


D
DarckBlezzer

I have tested all of this examples, I did a benchmark, and finally I recommend you choose the shorter one, it doesn't affect in performance.

Runned in Ubuntu server 14.04, nodejs v8.12.0 - 26/10/18

    let i = 0;
console.time("TRUE test1")
    i=0;
    for(;i<100000000;i=i+1){
        true ? 1 : 0;
    }
console.timeEnd("TRUE test1")


console.time("FALSE test2")
    i=0;
    for(;i<100000000;i=i+1){
        false ? 1 : 0;
    }
console.timeEnd("FALSE test2")

console.log("----------------------------")

console.time("TRUE test1.1")
    i=0;
    for(;i<100000000;i=i+1){
        true === true ? 1 : 0;
    }
console.timeEnd("TRUE test1.1")


console.time("FALSE test2.1")
    i=0;
    for(;i<100000000;i=i+1){
        false === true ? 1 : 0;
    }
console.timeEnd("FALSE test2.1")

console.log("----------------------------")

console.time("TRUE test3")
    i=0;
    for(;i<100000000;i=i+1){
        true | 0;
    }
console.timeEnd("TRUE test3")

console.time("FALSE test4")
    i=0;
    for(;i<100000000;i=i+1){
        false | 0;
    }
console.timeEnd("FALSE test4")

console.log("----------------------------")

console.time("TRUE test5")
    i=0;
    for(;i<100000000;i=i+1){
        true * 1;
    }
console.timeEnd("TRUE test5")

console.time("FALSE test6")
    i=0;
    for(;i<100000000;i=i+1){
        false * 1;
    }
console.timeEnd("FALSE test6")

console.log("----------------------------")

console.time("TRUE test7")
    i=0;
    for(;i<100000000;i=i+1){
        true & 1;
    }
console.timeEnd("TRUE test7")

console.time("FALSE test8")
    i=0;
    for(;i<100000000;i=i+1){
        false & 1;
    }
console.timeEnd("FALSE test8")

console.log("----------------------------")

console.time("TRUE test9")
    i=0;
    for(;i<100000000;i=i+1){
        +true;
    }
console.timeEnd("TRUE test9")

console.time("FALSE test10")
    i=0;
    for(;i<100000000;i=i+1){
        +false;
    }
console.timeEnd("FALSE test10")

console.log("----------------------------")

console.time("TRUE test9.1")
    i=0;
    for(;i<100000000;i=i+1){
        0+true;
    }
console.timeEnd("TRUE test9.1")

console.time("FALSE test10.1")
    i=0;
    for(;i<100000000;i=i+1){
        0+false;
    }
console.timeEnd("FALSE test10.1")

console.log("----------------------------")

console.time("TRUE test9.2")
    i=0;
    for(;i<100000000;i=i+1){
        -true*-1;
    }
console.timeEnd("TRUE test9.2")

console.time("FALSE test10.2")
    i=0;
    for(;i<100000000;i=i+1){
        -false*-1;
    }
console.timeEnd("FALSE test10.2")

console.log("----------------------------")

console.time("TRUE test9.3")
    i=0;
    for(;i<100000000;i=i+1){
        true-0;
    }
console.timeEnd("TRUE test9.3")

console.time("FALSE test10.3")
    i=0;
    for(;i<100000000;i=i+1){
        false-0;
    }
console.timeEnd("FALSE test10.3")

console.log("----------------------------")

console.time("TRUE test11")
    i=0;
    for(;i<100000000;i=i+1){
        Number(true);
    }
console.timeEnd("TRUE test11")

console.time("FALSE test12")
    i=0;
    for(;i<100000000;i=i+1){
        Number(false);
    }
console.timeEnd("FALSE test12")

console.log("----------------------------")

console.time("TRUE test13")
    i=0;
    for(;i<100000000;i=i+1){
        true + 0;
    }
console.timeEnd("TRUE test13")

console.time("FALSE test14")
    i=0;
    for(;i<100000000;i=i+1){
        false + 0;
    }
console.timeEnd("FALSE test14")

console.log("----------------------------")

console.time("TRUE test15")
    i=0;
    for(;i<100000000;i=i+1){
        true ^ 0;
    }
console.timeEnd("TRUE test15")

console.time("FALSE test16")
    i=0;
    for(;i<100000000;i=i+1){
        false ^ 0;
    }
console.timeEnd("FALSE test16")

console.log("----------------------------")

console.time("TRUE test17")
    i=0;
    for(;i<100000000;i=i+1){
        true ^ 0;
    }
console.timeEnd("TRUE test17")

console.time("FALSE test18")
    i=0;
    for(;i<100000000;i=i+1){
        false ^ 0;
    }
console.timeEnd("FALSE test18")

console.log("----------------------------")

console.time("TRUE test19")
    i=0;
    for(;i<100000000;i=i+1){
        true >> 0;
    }
console.timeEnd("TRUE test19")

console.time("FALSE test20")
    i=0;
    for(;i<100000000;i=i+1){
        false >> 0;
    }
console.timeEnd("FALSE test20")

console.log("----------------------------")

console.time("TRUE test21")
    i=0;
    for(;i<100000000;i=i+1){
        true >>> 0;
    }
console.timeEnd("TRUE test21")

console.time("FALSE test22")
    i=0;
    for(;i<100000000;i=i+1){
        false >>> 0;
    }
console.timeEnd("FALSE test22")

console.log("----------------------------")

console.time("TRUE test23")
    i=0;
    for(;i<100000000;i=i+1){
        true << 0;
    }
console.timeEnd("TRUE test23")

console.time("FALSE test24")
    i=0;
    for(;i<100000000;i=i+1){
        false << 0;
    }
console.timeEnd("FALSE test24")

console.log("----------------------------")

console.time("TRUE test25")
    i=0;
    for(;i<100000000;i=i+1){
        ~~true;
    }
console.timeEnd("TRUE test25")

console.time("FALSE test26")
    i=0;
    for(;i<100000000;i=i+1){
        ~~false;
    }
console.timeEnd("FALSE test26")

console.log("----------------------------")

console.time("TRUE test25.1")
    i=0;
    for(;i<100000000;i=i+1){
        ~true*-1-1;
    }
console.timeEnd("TRUE test25.1")

console.time("FALSE test26.1")
    i=0;
    for(;i<100000000;i=i+1){
        ~false*-1-1;
    }
console.timeEnd("FALSE test26.1")

console.log("----------------------------")

console.time("TRUE test27")
    i=0;
    for(;i<100000000;i=i+1){
        true/1;
    }
console.timeEnd("TRUE test27")

console.time("FALSE test28")
    i=0;
    for(;i<100000000;i=i+1){
        false/1;
    }
console.timeEnd("FALSE test28")

Result

TRUE test1: 93.301ms
FALSE test2: 102.854ms
----------------------------
TRUE test1.1: 118.979ms
FALSE test2.1: 119.061ms
----------------------------
TRUE test3: 97.265ms
FALSE test4: 108.389ms
----------------------------
TRUE test5: 85.854ms
FALSE test6: 87.449ms
----------------------------
TRUE test7: 83.126ms
FALSE test8: 84.992ms
----------------------------
TRUE test9: 99.683ms
FALSE test10: 87.080ms
----------------------------
TRUE test9.1: 85.587ms
FALSE test10.1: 86.050ms
----------------------------
TRUE test9.2: 85.883ms
FALSE test10.2: 89.066ms
----------------------------
TRUE test9.3: 86.722ms
FALSE test10.3: 85.187ms
----------------------------
TRUE test11: 86.245ms
FALSE test12: 85.808ms
----------------------------
TRUE test13: 84.192ms
FALSE test14: 84.173ms
----------------------------
TRUE test15: 81.575ms
FALSE test16: 81.699ms
----------------------------
TRUE test17: 81.979ms
FALSE test18: 81.599ms
----------------------------
TRUE test19: 81.578ms
FALSE test20: 81.452ms
----------------------------
TRUE test21: 115.886ms
FALSE test22: 88.935ms
----------------------------
TRUE test23: 82.077ms
FALSE test24: 81.822ms
----------------------------
TRUE test25: 81.904ms
FALSE test26: 82.371ms
----------------------------
TRUE test25.1: 82.319ms
FALSE test26.1: 96.648ms
----------------------------
TRUE test27: 89.943ms
FALSE test28: 83.646ms