1. toFixed() 方法:该方法将数字转换为字符串,并保留指定的小数位数。
let num = 3.1415926;
let result = num.toFixed(2);
// "3.14"
2. Math.round() 方法:该方法将数字四舍五入到指定的小数位数。
2. Math.round() 方法:该方法将数字四舍五入到指定的小数位数。
3. parseFloat() 和正则表达式:该方法将字符串转换为数字,并保留指定的小数位数。
let num = "3.1415926";
let result = parseFloat(num).toFixed(2);
// "3.14"
4. Number() 和正则表达式:该方法将字符串转换为数字,并保留指定的小数位数。
let num = "3.1415926";
let result = Number(num.match(/^\d+(?:\.\d{0,2})?/));
// 3.14
以上提供的方法,阅读者可以根据需求自行选取,你们的支持是我创作的动力。