文章目录
JavaScript 数学对象
JavaScript 数学对象允许您对数字执行数学任务。
示例
Math.PI;
数学对象
与其他对象不同,数学对象没有构造函数。
数学对象是静态的。
无需先创建数学对象即可使用所有方法和属性。
数学属性(常量)
任何数学属性的语法都是:Math.property。
JavaScript 提供了 8 个数学常量,可以作为 Math 属性访问:
示例
Math.E // 返回欧拉数
Math.PI // 返回 PI
Math.SQRT2 // 返回 2 的平方根
Math.SQRT1_2 // 返回 1/2 的平方根
Math.LN2 // 返回 2 的自然对数
Math.LN10 // 返回 10 的自然对数
Math.LOG2E // 返回以 2 为底的 E 对数
Math.LOG10E // 返回以 10 为底的 E 对数
Math 方法
Math 任何方法的语法为:Math.method(number)
数字转整数
有 4 种常用方法将数字四舍五入为整数:
Math.round(x) 返回将 x 四舍五入为最接近的整数
Math.ceil(x) 返回将 x 四舍五入为最接近的整数
Math.floor(x) 返回四舍五入后的 x向下舍入到最接近的整数
Math.trunc(x) 返回 x 的整数部分(ES6 中的新功能)
Math.round()
Math.round(x) 返回最接近的整数:
示例
Math.round(4.6);
Math.round(4.5);
Math.round(4.4);
Math.ceil()
Math.ceil(x) 返回向上舍入到最接近的整数的 x 值:
示例
Math.ceil(4.9);
Math.ceil(4.7);
Math.ceil(4.4);
Math.ceil(4.2);
Math.ceil(-4.2);
Math.floor()
Math.floor(x) 返回向下舍入到最接近的整数的 x

最低0.47元/天 解锁文章
531

被折叠的 条评论
为什么被折叠?



