Home >Web Front-end >JS Tutorial >How to round division in js
In JavaScript, the following two methods can be used to round the result of division: The Math.floor() method returns the value of the floating point number after rounding down. The symbol "|" performs bitwise OR operation, truncates the decimal part and returns an integer.
#How to get the result of integer division in JS?
In JavaScript, the result of division is usually a floating point number. However, sometimes we may need to round the results. To achieve this, there are two common ways:
1. Use the Math.floor() method
The Math.floor() method returns a floating point number downward The rounded value. For example:
<code class="javascript">const result = Math.floor(10 / 3); // 结果为 3</code>
2. Use the symbol "|"
In JavaScript, the symbol "|" can be used to perform bit operations. When used with numbers, it performs a bitwise OR operation on the numbers, truncating the fractional part and returning an integer. For example:
<code class="javascript">const result = 10 / 3 | 0; // 结果为 3</code>
Compare
There is no significant difference in performance between these two methods. However, the Math.floor() method is easier to understand, and the notation "|" may be more concise in some cases.
Example
Here is an example of round division using both methods:
<code class="javascript">const num1 = 10; const num2 = 3; console.log("使用Math.floor()取整:", Math.floor(num1 / num2)); console.log("使用\"|\"取整:", num1 / num2 | 0);</code>
Output:
<code>使用Math.floor()取整: 3 使用"|"取整: 3</code>
The above is the detailed content of How to round division in js. For more information, please follow other related articles on the PHP Chinese website!