js常用的保留小数的方法:
1、toFixed()
例如:
let val=100 console.log(val.toFixed(2))//100.00 val=100.005 console.log(val.toFixed(2))//100.00 val=100.0050 console.log(val.toFixed(2))//100.00 val=100.0051 console.log(val.toFixed(2))//100.01
这种方法大部分场合都适用,但是存在尾数是5的时候会不进位的问题
2、Math.round()
例如:
let val1=100.00 console.log(Math.round(val1*100)/100)//100 val1=100.01 console.log(Math.round(val1*100)/100)//100.01
这种方法存在当数字是整数或者小数点后数字为0,或者原数字长度比我们要保留的长度短时,保留有问题的情况
3、封装方法,适用所有场合,并完全符合数学中的四舍五入规则
// val要保留的数据,places保留位数,type返回类型(1数字,2字符串) function keepDecimals(val, places, type) { let num = val + ''; let numStart = num.split('.')[0] let numEnd = num.split('.')[1] let powVal = Math.pow(10, places) if (numEnd) { console.log(numEnd,111) num = Math.round(num * powVal) / powVal + '' if (num.split('.')[1]&&num.split('.')[1].length < places) { for (let n = 0; n < places - num.split('.')[1].length; n++) { num += '0' } } } else { num = numStart + '.' for (let n = 0; n < places; n++) { num += '0' } } return type==1?num=num*1:num=num+'' } let num = keepDecimals(10, 3, 2)