Home >Web Front-end >JS Tutorial >How to use the built-in object Math of javascript objects_Basic knowledge

How to use the built-in object Math of javascript objects_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 18:29:131241browse
1. Math.min() and Math.max(), return the minimum and maximum values ​​in the parameters respectively
Example:
alert(Math.min(1,2,3)) //Output "1"
Alert(Math.max(1,2,3)) //Output "3"

2. Math.abs(), returns the absolute value of the parameter
Example:
alert(Math.abs(-1)) //Output "1"

3. Math.random(), generates a 0 to 1 Random number
Example:
window.open("http://www.***.com/index.shtml?t=" Math.random) //Add a after the url address The parameter whose value is a random number can ensure that the page is re-pulled from the server every time instead of reading the cache.

4. Math.floor(), Math.round(), Math.ceil()
Math.floor(): Round decimals down to integers. Example: alert(Math.floor(1.5)) //Output "1"
Math.round(): Round decimals into integers Example: alert(Math.round(1.5)) //Output "2"
Math.ceil(): Round up the decimal to an integer. Example: alert(Math.round(1.5)) //Output "2"
Using these three functions, it is very convenient when it comes to decimal calculations, such as Design the following function to process decimals
Copy code The code is as follows:

 function test(num, flag, bit) //The parameters are the decimal "num" to be passed in; the rounding standard (-1, downward; 0, standard; 1 upward) "flag"; the number of decimal places to retain "bit"
 {
var n=Math.pow(10,bit);
switch(flag)
case -1:return Math.floor(num*n)/n;break; case 0:return Math.round(num*n)/n; break;
case 1: return Math.ceil(num*n)/n;
Statement:
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