在JavaScript中如何按自己的需求保留指定位数的小数呢,总结了两个方法
1.使用Math.round的方法
Math.round的方法:将一个数四舍五入
let a=6.6666
// 保留两位小数
let result=Math.round(a*100)/100
// 输出6.67
alert(result)
// 保留一位小数
result=Math.round(a*10)/10
// 输出6.7
alert(result)
2. 使用toFixed()方法
toFixed(填写要保留的小数位数):保留指定小数位数
let a=6.6666
// 保留两位小数
let result=a.toFixed(2)
// 输出6.67
alert(result)
// 保留一位小数
result=a.toFixed(1)
// 输出6.7
alert(result)