js实现数字每三位加逗号

需求:

一个数字,比如 1234,23456.23 实现每三位加逗号

改成如下形式:

1234 => 1,234

23456.23 => 23,456.23

 

方法一

function formateNum (num) {
    let str = String(num);
    let strStart = str, strEnd = ''
    if (str.indexOf('.') != -1) {
      strStart = str.split('.')[0];
      strEnd = str.split('.')[1];
    }
    let len = strStart.length;
    let count = 0;
    let newStr = ''
    for (let i = len - 1; i >= 0; i--) {
      if (count % 3 == 0 && count != 0) {
        newStr = strStart[i] + ',' + newStr
      } else {
        newStr = strStart[i] + newStr;
      }
      count++;
    }
    if (strEnd) {
      newStr = newStr + '.' + strEnd;
    }
    return newStr;
  }
  let num = 129874.78;
  console.log(formateNum(num)); // 129,874.78
  let num1 = 33245;
  console.log(formateNum(num1)); // 33,245

 

方法二:

/**
 * 12345 => $12,345.00
 *
 * @param  {[type]} value    [description]
 * @param  {[type]} currency [description]
 * @return {[type]}          [description]
 */
function currency(value, currency) {

  value = parseFloat(value)

  if (!isFinite(value) || (!value && value !== 0)) {

    return ''
  }

  currency = currency !== null ? currency : '$'
  let stringified = Math.abs(value).toFixed(2)
  let _int = stringified.slice(0, -3)
  let i = _int.length % 3
  let head = i > 0
    ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
    : ''
  let _float = stringified.slice(-3)
  let sign = value < 0 ? '-' : ''

  return currency + sign + head +
    _int.slice(i).replace(digitsRE, '$1,') +
    _float
}

 

posted on 2018-03-29 13:09  前端开发小柒  阅读(251)  评论(0编辑  收藏  举报

导航