The function of the js operator single vertical bar "|"
When operating js integers, it is equivalent to removing the decimal point, parseInt. When a positive number is equivalent to Math.floor(), and when a negative number is equivalent to Math.ceil() Note:
1. Math.ceil() is used as upward rounding.
2. Math.floor() is used as rounding downwards.
3. Math.round() Round() commonly used in mathematics.
console.log(0.6|0)//0console.log(1.1|0)//1console.log(3.65555|0)//3console.log(5.99999|0)//5console.log(-7.777|0)//-7
Note: In addition to the three methods of Math to process numbers, we often use parseInt(), parseFloat(), toFixed() and toPrecision(), etc. A brief explanation:
The usage of the toFixed method is as follows:
100.456001.toFixed(2); //100.47100.456001.toFixed(3); //100.456Number.prototype.toFixed.call(100.456001,2); //100.47
Disadvantages: After use, it will become a string.
ToPrecision usage is as follows:
99.456001.toPrecision(5); //99.456100.456001.toPrecision(5); //100.46Number.prototype.toPrecision.call(10.456001,5); //10.456
Operation rules for single vertical bars
After looking at the above example, we generally know that a single vertical bar can perform rounding operation, which means that only the positive part is retained and the decimal part is removed, but how does "|0" be calculated? Why can "|0" achieve the purpose of rounding? What will be the single vertical bar be if it is not 0?
With these questions in mind, let's look at the following example:
console.log(3|4); //7console.log(4|4); //4console.log(8|3); //11console.log(5.3|4.1); //5console.log(9|3455); //3455
OK, I'll announce the answer here. In fact, the single vertical bar "|" is the result obtained by converting it to 2-digit system. For example, let’s take a simple example:
Copy the code as follows: 3|4
After converting to binary, 011|100 is added to get 111=7
Copy the code as follows: 4|4
After converting to binary, 100 | 100 is added to get 100=4
Copy the code as follows: 8|3
After converting to binary, 1000 |011 adds to get 1011=11