JavaScript实现货币格式转换与数字解析

作者:工具松鼠

时间:2026-10-30

浏览:70

本文介绍两种JavaScript处理货币格式的方法:一是通过扩展Number原型实现自定义货币字符串格式化,支持指定小数位、符号及分隔符;二是利用正则表达式去除货币符号,将格式化后的字符串还原为纯净数字。内容涵盖代码示例、参数说明及非原型模式的替代方案,适用于前端数据展示与计算场景。

文章目录

JavaScript货币格式化方法

首先介绍一种使用JavaScript将数字转换为货币格式字符串的方法。该函数接收四个参数:保留的小数位数、货币符号、整数部分的千位分隔符以及小数部分的分隔符。

其次介绍另一种方法,通过简单的正则表达式将货币格式的字符串转换为纯净的数字字符串,随后可将该字符串转换为数字类型。以下代码展示了如何扩展Number原型来实现货币格式化功能。


// Extend the default Number object with a formatMoney() method:
// usage: someVar.formatMoney(decimalPlaces, symbol, thousandsSeparator, decimalSeparator)
// defaults: (2, "$", ",", ".")
Number.prototype.formatMoney = function (places, symbol, thousand, decimal) {
  places = !isNaN(places = Math.abs(places)) ? places : 2;
  symbol = symbol !== undefined ? symbol : "$";
  thousand = thousand || ",";
  decimal = decimal || ".";
  var number = this,
    negative = number < 0 ? "-" : "",
    i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
    j = (j = i.length) > 3 ? j % 3 : 0;
  return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
};

以下是具体的转换示例:


// Default usage and custom precision/symbol :
var revenue = 12345678;
alert(revenue.formatMoney()); // $12,345,678.00
alert(revenue.formatMoney(0, "HK$ ")); // HK$ 12,345,678

// European formatting:
var price = 4999.99;
alert(price.formatMoney(2, "€", ".", ",")); // €4.999,99

// It works for negative values, too:
alert((-500000).formatMoney(0, "£ ")); // £ -500,000

货币字符串转数字解析

接下来展示如何将货币字符串转换为数字,即去除货币格式化符号的过程。该过程使用正则表达式进行过滤处理。


var price = (12345.99).formatMoney(); // "$12,345.99"

// Remove non-numeric chars (except decimal point/minus sign):
priceVal = parseFloat(price.replace(/[^0-9-.]/g, '')); // 12345.99

上述正则表达式仅适用于小数分隔符为英文句点(.)的情况。若小数分隔符为逗号(,),则正则表达式应调整为/[^0-9-,]/g。

如果不希望使用原型扩展Number对象,可以使用以下不依赖原型的版本:


// To set it up as a global function:
function formatMoney(number, places, symbol, thousand, decimal) {
  number = number || 0;
  places = !isNaN(places = Math.abs(places)) ? places : 2;
  symbol = symbol !== undefined ? symbol : "$";
  thousand = thousand || ",";
  decimal = decimal || ".";
  var negative = number < 0 ? "-" : "",
    i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
    j = (j = i.length) > 3 ? j % 3 : 0;
  return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
}

// To create it as a library method:
myLibrary.formatMoney = function (number, places, symbol, thousand, decimal) {
  /* as above */
}

// Example usage:
formatMoney(54321); // $54,321
myLibrary.formatMoney(12345, 0, "£ "); // £ 12,345

以上即为本文的全部内容。如需进一步了解JavaScript语法,建议查阅《JavaScript 参考教程》与《JavaScript代码风格指南》,也欢迎大家继续支持本站。

实用工具推荐

电子包浆

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

使用 ›
图片压缩

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

使用 ›
相关文章