javascript中保留两位小数

不进行四舍五入,并且强制保留两位小数或者多位小数

/**
* if判断num是否包含小数点,返回-1不包含,非-1包含
* 如果不包含小数点,直接使用toFixed方法保留两位小数
* 如果包含小数点,则吧num转为字符串进行截取,从0开始,一直到小数点下标+3(indexOf方法返回
* 小数点首次出现位置,返回该索引),然后我们转为数字在进行保留两位小数,避免自动舍0。
*/
function mathFloat(num) {
    if (num.toString().indexOf('.') == -1) {
        console.log(Number(num).toFixed(2)) // => -8.00
        return Number(num).toFixed(2)
    } else {
        console.log(Number(String(num).substring(0, String(num).indexOf('.') + 3)).toFixed(2))
        return Number(String(num).substring(0, String(num).indexOf('.') + 3)).toFixed(2)
    }
}
mathFloat(-8)

Math.round(num)保留整数,该方法四舍五入

Math.round(6.8); 	// 返回7
Math.round(6.1999); // 返回6

Math.pow(x,y)乘方,返回的是 X的y次幂

Math.pow(9,2);  // 返回81
Math.pow(2,3);  // 返回8

Math.sqrt(x)返回x的平方

Math.sqrt(3);	//返回9

Math.abs(x)返回x的绝对值

Math.abs(-4.7);	//返回4.7
Math.abs(3.7);	//返回3.7

Math.ceil(x)向上取整

Math.ceil(6.1); //返回7

Math.floor(x)向下取整

Math.floor(2.9); //返回2

Math.min() 和 Math.max()返回最小值和最大值

Math.min(10,20,8,333); //返回8
Math.max(10,20,8,333); //返回333

Math.random()返回0——1随机数

Math.random(); //返回0——1随机数

如果该文章你对你有帮助,请点个赞,也希望能多多提意见,感谢参考


版权声明:本文为qq_44979541原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。