JS 中的 Math

JS中关于Math的一些方法有的时候经常会忘记,想着写一篇博客记录一下有助于记下一些常用的方法,以便到时候不需要再去看下Mdn的文档了。

Math.abs()

函数返回指定数字”x”的绝对值。

传入一个非数字形式的字符串或者 undefined/empty 变量,将返回 NaN。传入 null 将返回 0。

1
2
3
4
5
Math.abs('-1');     // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs("string"); // NaN
Math.abs(); // NaN

Math.ceil()

向上取整。

1
2
3
4
5
6
Math.ceil(.95);    // 1
Math.ceil(4); // 4
Math.ceil(7.004); // 8
Math.ceil(-0.95); // -0
Math.ceil(-4); // -4
Math.ceil(-7.004); // -7

Math.floor()

向下取整。

1
2
3
4
5
Math.floor(45.95);   // 45 
Math.floor(45.05); // 45
Math.floor(4); // 4
Math.floor(-45.05); // -46
Math.floor(-45.95); // -46

Math.round()

函数返回一个数字四舍五入后最接近的整数。

注意:Math.round()在处理负数的时候会有些不同特别是在小数部分恰好是0.5的情况下。

1
2
3
4
x = Math.round(20.49);   //20
x = Math.round(20.5); //21
x = Math.round(-20.5); //-20
x = Math.round(-20.51); //-21

Math.max() / Math.min()

Math.max()函数返回一组数中的最大值。Math.min() 函数返回一组数中的最小值。

注意:当没有参数传入的时候Math.max()返回-Infinity。 Math.min()返回Infinity。

hi you can see me