保留兩位小數不進行四舍五入
// 保留小數n位,不進行四舍五入
// num你傳遞過來的數字,
// decimal你保留的幾位,默認保留小數后兩位
app.config.globalProperties.formatDecimal = function (
num,
decimal = 2
) {
num = num.toString()
const index = num.indexOf('.')
if (index !== -1) {
num = num.substring(0, decimal + index + 1)
} else {
num = num.substring(0)
}
//截取后保留兩位小數
return parseFloat(num).toFixed(decimal)
}
原理
進行截取,使用的是substring();包含起始位,不包含結束位
這樣就不會進行四舍五入了
最后為啥要使用toFixed。
我們都知道toFixed會進行四舍五入的.
toFixed(2)是為了顯示兩位小數