// 1.toFixed方法。————》四舍五入
let num = 46.123456;
let numTo = num.toFixed(2)
console.log(numTo) // 46.12
let num2 = 46.12743;
let numTo2 = num2.toFixed(2)
console.log(numTo2) // 46.13
// 2.通过substring截取。————》直接截取
let num = 46.123456;
let s = num.toString();
let result = s.substring(0,s.indexOf(".")+3); //截取小数点后2位
let result2 = s.substring(0,s.indexOf(".")+5); //截取小数点后4位
console.log(result); // 46.12
console.log(result2); // 46.1234
// 3. 正则表达式。————》直接截取
let num = 22.123456;
let re = /([0-9]+\.[0-9]{2})[0-9]*/;
let aNew = num.toString().replace(re,"$1");
console.log(aNew);// 22.12
// 4.数据类型保留上。————》四舍五入
let num=22.123456;
console.log( Math.round(num*10000)/10000); // 22.1235
console.log( Math.round(num*1000)/1000); // 22.123
console.log( Math.round(num*100)/100); // 22.12
console.log( Math.round(num*10)/10);// 22.1
js取小数点后两位(四舍五入、直接截取)
最新推荐文章于 2023-07-21 09:20:29 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)