JavaScript-数字(整数、浮点数)千分位格式化

10,639 阅读1分钟
在一些业务场景,例如金额、次数等数字需要进行千分位格式化
  • 原生方法(整数千分位格式化)

     /**
       * 将整数格式化成每 3 位添加一个逗号
       * @param {Number} num 待格式化的数字
       * @returns {String} 返回格式化后的数字
       */
      Vue.prototype.$wFormatInt = num => {
        let numPrefix = ''
        let numArr = ''
        let numDist = ''
    
        // 处理负数情况
        if (num < 0) {
          numPrefix = '-'
          numArr = String(num).slice(1).split('').reverse()
        } else {
          numArr = String(num).split('').reverse()
        }
    
        for (let i = 0; i < numArr.length; i++) {
          numDist += numArr[i]
          if ((i + 1) % 3 === 0 && (i + 1) < numArr.length) {
            numDist += ','
          }
        }
    
        return numPrefix + numDist.split('').reverse().join('')
      }

  • 原生方法(浮点数)

    /**
       * 将浮点数格式化成每 3 位添加一个逗号
       * @param {Number} money 待格式化的金额
       * @returns {String} 返回格式化后的数字
       */
      Vue.prototype.$wFormatDeci = num => {
        let numDeci = String(num).slice(-3)
        let numInt = String(num).slice(0, -3)
        let numDist = Vue.prototype.$wFormatInt(numInt)
        return numDist + numDeci
      }


  • 正则表达式

     /**   * 将数字格式化成每 3 位添加一个逗号   * @param {Number} money 待格式化的金额   * @returns {String} 返回格式化后的数字   */
     Vue.prototype.$wFormatBoth = num => return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")

  • toLocaleString方法(代码量最少的一种方法)

    /**  * 将数字格式化成每 3 位添加一个逗号  * @param {Number} num 待格式化的数字  * @returns {String} 返回格式化后的数字  */
    Vue.prototype.$wFormatInt = num => num.toLocaleString('en-US')

 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

MDN文档上对这个方法的解析是:toLocaleString(locale, options) 方法返回这个数字在特定语言环境下的表示字符串。

此方法第一个参数为语言格式,不填时返回使用默认的语言环境和默认选项格式化的字符串

var number = 3500;

console.log(number.toLocaleString()); // Displays "3,500" if in U.S. English locale

不同地区数字格式的差异

var number = 123456.789;

// 德国使用逗号作为小数分隔符,分位周期为千位
console.log(number.toLocaleString('de-DE'));
// → 123.456,789

// 在大多数阿拉伯语国家使用阿拉伯语数字
console.log(number.toLocaleString('ar-EG'));
// → ١٢٣٤٥٦٫٧٨٩

// 印度使用千位/拉克(十万)/克若尔(千万)分隔
console.log(number.toLocaleString('en-IN'));
// → 1,23,456.789

// nu 扩展字段要求编号系统,e.g. 中文十进制
console.log(number.toLocaleString('zh-Hans-CN-u-nu-hanidec'));
// → 一二三,四五六.七八九

通过 toLocaleString 返回的结果可以通过 options 参数进行定制:

var number = 123456.789;

// 要求货币格式
console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// → 123.456,79 €

// 日元不使用小数位
console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// → ¥123,457

// 限制三位有效数字
console.log(number.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
// → 1,23,000