In JavaScript, |single vertical bars are usually used to collect evidence on floating-point numbers. Here we also introduce the operation rules of single vertical bars. Let’s explain in detail how to use |single vertical bars in JavaScript
The role of js operator single vertical bar "|"
When operating js integers, it is equivalent to removing the decimal point, parseInt. When it is a positive number, it is equivalent to Math.floor(), when it is a negative number, it is equivalent to Math.ceil() Note:
1. Math.ceil() is used to round up.
2. Math.floor() is used to round down.
3. Math.round() Rounding is commonly used in our mathematics.
console.log(0.6|0)//0 console.log(1.1|0)//1 console.log(3.65555|0)//3 console.log(5.99999|0)//5 console.log(-7.777|0)//-7
Note: In addition to Math’s three methods for processing numbers, we also often use parseInt(), parseFloat(), toFixed(), toPrecision(), etc. Simple explanation: The
toFixed method is used as follows:
100.456001.toFixed(2); //100.47 100.456001.toFixed(3); //100.456 Number.prototype.toFixed.call(100.456001,2); //100.47
Disadvantage: It will become a string after use.
toPrecision usage is as follows:
99.456001.toPrecision(5); //99.456 100.456001.toPrecision(5); //100.46 Number.prototype.toPrecision.call(10.456001,5); //10.456
Operation rules for single vertical bars
After reading the above example, we generally know that single vertical bars can be rounded The operation is to keep only the positive part and remove the decimal part. But how is "|0" calculated? Why can "|0" achieve the purpose of rounding? If the horizontal and vertical bar is not 0, what would it be?
With these questions, let’s look at the following example:
console.log(3|4); //7 console.log(4|4);//4 console.log(8|3);//11 console.log(5.3|4.1);//5 console.log(9|3455);//3455
Okay, let me publish the answer here. In fact, the single vertical bar "|" is the result of the addition after converting to binary. For example, let’s take a simple example:
3|4
After converting to binary, 011|100 is added to get 111=7
4|4
After converting to binary, 100 | 100 is added to get 100 = 4
8|3
After being converted to binary, 1000 | 011 is added to get 1011=11
The above is me I compiled it for everyone, I hope it will be helpful to everyone in the future.
Related articles:
Javascript array loop traversal (detailed explanation of forEach)
The above is the detailed content of Detailed explanation of how to use the | single vertical bar operator in JavaScript (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!