js 小数转换成%百分比 数字转换成货币写法

2020-03-31  本文已影响0人  IamaStupid
// 0.007 -> 0.7%
function changeToPrecent (num) {
  let res = ''
  if (num !== undefined) {
    if (typeof num === 'string' && num.substr(-1, 1) === '%') {
      // 12.3%
      let beforeStr = num.substring(0, num.length - 1)
      if (!isNaN(beforeStr - 0)) {
        res = num
      }
    } else if (!isNaN(num - 0)) {
      // 数字 或 数字字符串 '12.9' 1.1
      num = (num - 0) * 100
      // 注意这种情况:0.7 * 100 = 0.7000000000001
      res = num.toFixed(2) + '%'
    }
  }
  return res
}
// 1235 -> 1,235
function numberToMoney (num) {
  let res = ''
  if (num !== undefined && !isNaN(num - 0)) {
    num = num + ''
    let numArr = num.split('.')
    let strLen = numArr[0].length
    let n = 0
    for (let i = strLen - 1; i > -1; i--) {
      n++
      if (n % 3 === 0 && i > 0) {
        res = ',' + numArr[0].charAt(i) + res
      } else {
        res = numArr[0].charAt(i) + res
      }
    }
  }
  return res
}
上一篇 下一篇

猜你喜欢

热点阅读