Common methods of JavaScript Math

Math is a built-in object of JavaScript that provides some mathematical properties and methods to perform calculations on numbers (for the Number type ). Math is different from other global objects, it is not a constructor, all methods and properties of math are static, directly use and pass in the corresponding parameters.

1. Math.abs()
Math.abs() function returns the absolute value of a number

Math.abs(-10)
// 10

2.Math.ceil()
The Math.ceil() function returns the smallest integer greater than or equal to a given number.

Math.ceil(5.4) 
// 6

3. Math.cos()
The Math.cos() function returns the cosine of a value.

Math.sin(90 * Math.PI / 180)
// 1

4. Math.floor()
Math.floor() method returns the largest integer less than or equal to a given number

Math.floor(5.7) 
// 5
Math.floor(8.6)
// 8

5. Math.min()
The Math.min() method can return the minimum value in a specified set of data.

Math.min( 0, 100, -200, -140)
//-200

/ 如果没有参数,则结果为Infinity
Math.min()
// Infinity

// 如果有一项参数不能被转为数值,则结果为NaN

Math.min([99, 32], -2, -3) 
// NaN

6.Math.max()
The Math.max() method can return the maximum value in the specified data.

Math.max(0, 100, -200, -140) 
// 100

// 如果没有参数,则结果为-Infinity
Math.max()
// -Infinity

// 如果有一项参数不能被转为数值,则结果为NaN

Math.max([99, 32], -2, -3) 
// NaN

7. Math.round()
Math.round() returns an integer rounded to a number.

Math.round(5.7) 
// 6
Math.round(5.4) 
// 5
//修改js  四舍五入 并且保留两位小数 
	roundFixed(num, fixed) {
	     var pos = num.toString().indexOf('.'),
	     decimal_places = num.toString().length - pos - 1,
	     _int = num * Math.pow(10, decimal_places),
	     divisor_1 = Math.pow(10, decimal_places - fixed),
	     divisor_2 = Math.pow(10, fixed);
	     return Math.round(_int / divisor_1) / divisor_2;
	 },

8. Math.sqrt()
The Math.sqrt() method returns the square root of a number.

Math.sqrt(4) 
// 2
Math.sqrt(25) 
// 5

9. Math.pow()
The Math.pow() method returns the base (base) to the power of the exponent (exponent).

Math.pow(4, 2) 
// 16

10. Math.random()
The Math.random() function returns a floating point, a pseudo-random number ranging from 0 to less than 1, excluding 1 from 0 up.

Math.random()
//0.7050350570707662

11. Math.sin()
The Math.sin() function returns the sine of a value.

Math.sin(90 * Math.PI / 180)
// 1

12. Math.trunc()
The Math.trunc() function returns the integer part of a number, regardless of positive or negative numbers, directly removes the decimal point and the following part.

Math.trunc(13.37)    
// 13
Math.trunc(42.84)   
// 42
Math.trunc(0.123)   
//  0
Math.trunc(-0.123)   
// -0
Math.trunc("-1.123")
// -1
Math.trunc(NaN)      
// NaN
Math.trunc("foo")    
// NaN
Math.trunc()         
// NaN

Guess you like

Origin blog.csdn.net/lwzhang1101/article/details/129425636