代码
function formatDecimal(num, decimal) {
num = num.toString()
let index = num.indexOf('.')
if (index !== -1) {
num = num.substring(0, decimal + index + 1)
} else {
num = num.substring(0)
}
return parseFloat(num).toFixed(decimal)
}
- formatDecimal(23.45678, 2) —— 23.45
- formatDecimal(23.4999999, 2) —— 23.49
- formatDecimal(23.80, 2) —— 23.80
- formatDecimal(123456, 2) —— 123456.00
- formatDecimal(23.45678, 3) —— 23.456
- formatDecimal(23.45678, 4) —— 23.4567