目录
Math库和toFixed方法都是对JS中的数字(Number)类型进行操作的。
一、Math库中常用方法和属性
Math库中保存着许多数学中的方法,该库是浏览器自带的库,不需要我们手动的创建。
1、Math.PI
该属性保存的是圆周率,可以快速的得到圆周率,从而用于计算圆的相关东西。
2、取整
1)、Math.ceil()
向上取整,只要是小数,就会变成比原来大的整数。
console.log(Math.ceil(3.1)) //4
console.log(Math.ceil(3.5)) //4
注意:小数位数不能超过15位,超过后会失效。
2)、Math.floor()
向下取整,只要是小数,无论超过多少,都省略小数部分,变成比原来小的整数,和parseInt类似。
console.log(Math.ceil(3.1)) //3
console.log(Math.ceil(3.5)) //3
3)、Math.round()
小数会进行四舍五入,但只看第一位小数。
console.log(Math.round(3.45)) //3
3、Math.abs()
取绝对值。
console.log(Math.abs(-10)) //10
4、Math.sqrt()
开方,只能得到算术平方根。
console.log(Math.sqrt(25)) //5
5、Math.pow(底数,指数)
乘方,按照指定的底数和指数算出结果。
console.log(Math.pow(3,3)) //27
6、Math.max(多个值)和Math.min(多个值)
找出多个值中的最大值和最小值。
console.log(Math.max(5,10,60,50)) //60
console.log(Math.min(5,10,60,50)) //5
但不支持传入数组参数,比较数组的最大值和最小值
解决:Math.max/min.apply(Math,arr)
7、Math.random()
产生0-1之间的随机小数,但不包括1。
console.log(Math.random())
二、随机整数案例
1、0-10的随机整数(不包含10)
var res = Math.floor(Math.random() * 10);
console.log(res);
2、0-10的随机整数(包含10)
var res=Math.floor(Math.random()*(10+1))
console.log(res)
3、10-20的随机整数(不包含20)
var res = Math.floor(Math.random() * 10)+10;
console.log(res);
4、10-20的随机整数(包含10)
var res = Math.floor(Math.random() * 11)+10;
console.log(res);
5、封装一个产生随机数的函数(不包含最大值)
function getRandom(min,max){
if(min>max){
console.error("参数有误")
return
}
return Math.floor(Math.random()*(max-min))+min
}
6、封装一个产生随机数的函数(包含最大值)
function getRandom(min,max){
if(min>max){
console.error("参数有误")
return
}
return Math.floor(Math.random()*(max-min+1))+min
}
三、toFixed的使用
toFixed的作用是保留执行位数的小数,在保留的同时会四舍五入。
使用:变量.toFixed(n)
var price=3.1415
console.log(price.toFixed(2)) //3.14
如果原本的位数比要保留的位数小,会自动补0。
var price2=123.4
console.log(price2.toFixed(2)) //123.40
注意:toFixed的返回类型是【字符串】,所以需要进行类型转换之后才可以计算。
四、toFixed的底层原理实现
function tofixed(num, n) {
// 要取多少位小数,先乘10的多少次方
num *= Math.pow(10, n);
// 再四舍五入取整,因为toFixed有四舍五入
num = Math.round(num);
// 再除以10的多少次方就是保留多少位的小数了
num /= Math.pow(10, n);
console.log(num);
return num;
}
tofixed(Math.PI, 2);