美文网首页
js 小数转换成%百分比 数字转换成货币写法

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

作者: IamaStupid | 来源:发表于2020-03-31 15:40 被阅读0次
// 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
}

相关文章

网友评论

      本文标题:js 小数转换成%百分比 数字转换成货币写法

      本文链接:https://www.haomeiwen.com/subject/bogwuhtx.html