zoukankan      html  css  js  c++  java
  • 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
    }
  • 相关阅读:
    CentOS7系统基本操作
    python3安装
    nodejs基础【持续更新中】
    基于Jenkins实现持续集成【持续更新中】
    git之merge和rebase的区别
    服务器为什么这么慢?耗尽了CPU、RAM和磁盘I/O资源
    编程的四个境界
    Gunicorn独角兽
    Python 中 logging 日志模块在多进程环境下的使用
    vue+webpack怎么分环境进行打包
  • 原文地址:https://www.cnblogs.com/aimee2004/p/8669206.html
Copyright © 2011-2022 走看看