Math对象中的常用方法

2022-08-19  本文已影响0人  未路过

Math 对象不是构造函数,所以我们不需要new来调用,而是直接使用里面的属性和方法就可以。
可以使用它的如下方法

1. 绝对值方法

Math.abs(1);//1
Math.abs(-1)//1
Math.abs('-1')//隐士转换 会把字符串-1转换为数字型
Math.abd('pink')//NaN

2. 3个取整方法

//三个取整方法
//(1) Math.floor() 往下取整,往最小了取值
Math.floor(11.46)=Math.floor(11.68)=Math.floor(11.5)=11
Math.floor(-11.46)=Math.floor(-11.68)=Math.floor(-11.5)=-12

//(2)Math.ceil()    往上取整, 往最大了取值
Math.ceil(11.46)=Math.ceil(11.68)=Math.ceil(11.5)=12
Math.ceil(-11.46)=Math.ceil(-11.68)=Math.ceil(-11.5)=-11

//(3)Math.round()   四舍五入

小数点后第一位<5
正数:Math.round(11.46)=11
负数:Math.round(-11.46)=-11

小数点后第一位>5
正数:Math.round(11.68)=12
负数:Math.round(-11.68)=-12

小数点后第一位=5
正数:Math.round(11.5)=12
负数:Math.round(-11.5)=-11
总结:(小数点后第一位)大于五全部加,等于五正数加,小于五全不加。
上一篇 下一篇

猜你喜欢

热点阅读