JavaScript 格式化金额的几种常见实现方式

作者:桌面漫游

时间:2026-10-31

浏览:655

本文介绍JavaScript中格式化金额的三种主流方法。首先解析Intl.NumberFormat构造函数与Number.prototype.toLocaleString的使用及兼容性;其次演示结合toFixed与正则替换的模板字符串方案;最后提供基于字符串递归与正则的自定义格式化函数实现,涵盖整数与小数处理。

文章目录

JavaScript 金额格式化

一、利用 Intl.NumberFormat 构造函数

此为 JavaScript 中处理金额格式化的主流方案。Intl.NumberFormat() 构造函数接收语言环境与配置选项两个参数。语言环境定义格式化的地域与语言标准,选项则包含控制格式化细节的属性集合。例如,可通过样式属性设定货币格式,通过货币属性指定具体币种。

const amount = 1234567.89;
const locale = "en-US";
const options = {
  style: "currency",
  currency: "USD",
};
const formattedAmount = new Intl.NumberFormat(locale, options).format(amount);
console.log(formattedAmount); //$1,234,567.89

二、利用 Number.prototype.toLocaleString 方法

执行金额格式化时,可调用 JavaScript 的 toLocaleString() 方法。该函数能将数值转换为符合本地化规范的字符串,并允许指定货币符号、小数位数及千位分隔符等格式特征。

代码示例如下:

美元

const amount = 1234567.89;
const formattedAmount = amount.toLocaleString("en-US", {
  style: "currency",
  currency: "USD",
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});
console.log(formattedAmount); //$1,234,567.89

人民币

const amount = 1234567.89;
const formattedAmount = amount.toLocaleString("zh-CN", {
  style: "currency",
  currency: "CNY",
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});
console.log(formattedAmount);

本示例中,数值变量 amount 调用 toLocaleString() 方法转换为本地化字符串,并配置了以下格式参数:

  • style: 'currency' 用于指定以货币格式展示数值。
  • currency: 'USD' 用于指定美元符号作为货币标识。
  • minimumFractionDigits: 2 用于设定最小保留两位小数。
  • maximumFractionDigits: 2 用于设定最大保留两位小数。

借助此方式,可快速简便地在 JavaScript 中实现金额格式化。需注意的是,toLocaleString() 方法在不同浏览器及操作系统间存在差异,务必进行兼容性测试与处理。

三、利用模板字符串结合 Number.prototype.toFixed 与正则替换

const amount = 1234567.89;
const formattedAmount = `¥${amount
  .toFixed(2)
  .replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
console.log(formattedAmount);

本示例通过 toFixed 确保金额保留两位小数,利用正则替换插入千位分隔符,最后借助模板字符串完成拼接。

js金额数字格式化

一.利用字符串操作方法进行格式化

①整数金额格式化:

function moneyFormat (num) {
      const len = num.length
      return len <= 3 ? num : this.moneyFormat(num.substr(0, len - 3)) + ',' + num.substr(len - 3, 3)
}
var num = 12345000
var res = moneyFormat(String(num))
console.log('result:', res) // '12,345,000'

②自定义保留decimal位小数,并使用split分隔符的数字格式化:

function moneyFormat (num, decimal = 2, split = ',') {
  /*
    parameter:
    num:格式化目标数字
    decimal:保留几位小数,默认2位
    split:千分位分隔符,默认为,
    moneyFormat(123456789.87654321, 2, ',') // 123,456,789.88
  */
  function thousandFormat (num) {
    const len = num.length
    return len <= 3 ? num : thousandFormat(num.substr(0, len - 3)) + split + num.substr(len - 3, 3)
  }
  if (isFinite(num)) { // num是数字
    if (num === 0) { // 为0
      return num.toFixed(decimal)
    } else { // 非0
      var res = ''
      var dotIndex = String(num).indexOf('.')
      if (dotIndex === -1) { // 整数
        res = thousandFormat(String(num)) + '.' + '0'.repeat(decimal)
      } else { // 非整数
        // js四舍五入 Math.round():正数时4舍5入,负数时5舍6入
        // Math.round(1.5) = 2
        // Math.round(-1.5) = -1
        // Math.round(-1.6) = -2
        // 保留decimals位小数
        const numStr = String((Math.round(num * Math.pow(10, decimal)) / Math.pow(10, decimal)).toFixed(decimal)) // 四舍五入,然后固定保留2位小数
        const decimals = numStr.slice(dotIndex, dotIndex + decimal + 1) // 截取小数位
        res = thousandFormat(numStr.slice(0, dotIndex)) + decimals
      }
      return res
    }
  } else {
    return '--'
  }
}
console.log('result:', moneyFormat(123456789.87654321)) // '123,456,789.88'

二.利用正则表达式进行格式化

①整数金额格式化:

function moneyFormat (num) {
      return String(num).replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
}
var num = 12345000
var res = moneyFormat(num)
console.log('result:', res) // '12,345,000'

②自定义保留decimal位小数,并使用split分隔符的数字格式化:

function moneyFormat (num, decimal = 2, split = ',') {
  /*
    parameter:
    num:格式化目标数字
    decimal:保留几位小数,默认2位
    split:千分位分隔符,默认为,
    moneyFormat(123456789.87654321, 2, ',') // 123,456,789.88
  */
  if (isFinite(num)) { // num是数字
    if (num === 0) { // 为0
      return num.toFixed(decimal)
    } else { // 非0
      var res = ''
      var dotIndex = String(num).indexOf('.')
      if (dotIndex === -1) { // 整数
        res = String(num).replace(/(\d)(?=(?:\d{3})+$)/g, `$1${split}`) + '.' + '0'.repeat(decimal)
      } else { // 非整数
        // js四舍五入 Math.round():正数时4舍5入,负数时5舍6入
        // Math.round(1.5) = 2
        // Math.round(-1.5) = -1
        // Math.round(-1.6) = -2
        // 保留decimals位小数
        const numStr = String((Math.round(num * Math.pow(10, decimal)) / Math.pow(10, decimal)).toFixed(decimal)) // 四舍五入,然后固定保留2位小数
        const decimals = numStr.slice(dotIndex, dotIndex + decimal + 1) // 截取小数位
        res = String(numStr.slice(0, dotIndex)).replace(/(\d)(?=(?:\d{3})+$)/g, `$1${split}`) + decimals
      }
      return res
    }
  } else {
    return '--'
  }
}
console.log('result:', moneyFormat(123456789.87654321)) // '123,456,789.88'

至此,关于JavaScript 格式化金额的讲解结束,更多相关js格式化金额内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章