JavaScript Math常用方法

math是JavaScript的一个内置对象,它提供了一些数学属性和方法,可以对数字进行计算(用于Number类型)。 math和其他全局对象不同,它不是一个构造器,math的所有方法和属性都是静态的,直接使用并传入对应的参数。

1.Math.abs()
Math.abs()函数,返回一个数的绝对值

Math.abs(-10)
// 10

2.Math.ceil()
Math.ceil()函数,返回大于或等于一个给定数的最小整数。

Math.ceil(5.4) 
// 6

3. Math.cos()
Math.cos()函数,返回一个值的余弦值。

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

4. Math.floor()
Math.floor()方法,返回小于或等于一个给定数字的最大整数

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

5.Math.min()
Math.min()方法,是可以返回指定一组数据中最小值。

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

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

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

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

6.Math.max()
Math.max()方法,是可返回指定数据中最大值。

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

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

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

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

7.Math.round()
Math.round(),返回的是一个数字四舍五入的整数。

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()
Math.sqrt()方法,返回的是一个数的平方根。

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

9. Math.pow()
Math.pow()方法,返回基数(base)的指数(exponent)次幂。

Math.pow(4, 2) 
// 16

10. Math.random()
Math.random()函数,返回一个浮点,伪随机数范围从0到小于1,从0往上不包括1。

Math.random()
//0.7050350570707662

11. Math.sin()
Math.sin()函数,返回一个值的正弦值。

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

12.Math.trunc()
Math.trunc()函数,返回的是一个数的整数部分,不管正数还是负数,直接去掉小数点及之后的部分。

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

猜你喜欢

转载自blog.csdn.net/lwzhang1101/article/details/129425636