js保留两位小数(不四舍五入)

 

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
posted @ 2020-05-19 17:07  expworld  阅读(14447)  评论(0)    收藏  举报