How to round division in js

下次还敢
Release: 2024-05-06 12:45:22
Original
660 people have browsed it

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 round division in js

#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:

const result = Math.floor(10 / 3); // 结果为 3
Copy after login

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:

const result = 10 / 3 | 0; // 结果为 3
Copy after login

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:

const num1 = 10; const num2 = 3; console.log("使用Math.floor()取整:", Math.floor(num1 / num2)); console.log("使用\"|\"取整:", num1 / num2 | 0);
Copy after login

Output:

使用Math.floor()取整: 3 使用"|"取整: 3
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!