Home > Web Front-end > JS Tutorial > body text

How JavaScript calculates division

藏色散人
Release: 2023-01-05 16:14:30
Original
14803 people have browsed it

JavaScript method of calculating division: 1. Implement division and rounding through "Math.round(x)"; 2. Implement division and round down through "Math.floor(x)"; 3. Through "Math.ceil(x)" implements division and rounding up.

How JavaScript calculates division

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

Division in Javascript

Today I will do an exercise and use JS to do paging. The formula used is:

totalPage =( totalNum-1)/numPerPage+1;
Copy after login

where totalPage represents the total number of pages, totalNum represents the length of all records returned, and numPerPage represents the number of rows displayed on each page. I have used this in java code before and there was no problem. But today when I used this formula in JS, something went wrong. The division operation "/" in JS could actually return a decimal, which was unexpected. .

Then I checked the information on the Internet and found a faster function, Math.ceil(x), rounded up, and it was done directly. .

// javascript除法如何取整
Math.round(x)  
// 四舍五入,如Math.round(0.60),结果为1;Math.round(0.49),结果为0;
Math.floor(x)   
//  向下舍入,如Math.floor(0.60)与Math.floor(0.49),结果均为0;
Math.ceil(x)   
//向上舍入,如Math.ceil(0.60)与Math.ceil(0. 49),结果均为1。
Copy after login

The division operation in JS ” / “Different from Java, the division operation in JS can return decimals, so pay special attention. .

Recommended study: "javascript Advanced Tutorial"

The above is the detailed content of How JavaScript calculates division. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template