我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
当前回答
Intl.NumberFormat(国际数字格式)
JavaScript有一个数字格式器(国际化API的一部分)。
//创建我们的数字格式器。const formatter=新Intl.NumberFormat('en-US'{style:'货币',货币:'美元',//如果你想要的话,这些选项需要四舍五入到整数。//minimumFractionDigits:0,//(这对于整数足够了,但将打印2500.10作为$2500.1)//maximumFractionDigits:0,//(导致2500.99打印为$2501)});console.log(formatter.format(2500));/*$2,500.00 */
使用undefined代替第一个参数(示例中为'en-US')来使用系统区域设置(如果代码在浏览器中运行,则为用户区域设置)。区域设置代码的进一步说明。
这是货币代码列表。
Intl.NumberFormat与Number.prototype.toLocaleString
最后一点,将其与旧的.toLocaleString进行比较。它们都提供了基本相同的功能。然而,toLocaleString在其旧版本(pre-Intl)中实际上不支持区域设置:它使用系统区域设置。因此,在调试旧浏览器时,请确保使用的是正确的版本(MDN建议检查Intl的存在)。如果你不关心旧浏览器或者只使用填充程序,那么根本不需要担心这一点。
此外,对于单个项目,两者的性能是相同的,但如果要格式化大量数字,则使用Intl.NumberFormat的速度要快70倍。因此,通常最好使用Intl.NumberFormat,并在每次页面加载时仅实例化一次。无论如何,下面是toLocaleString的等效用法:
console.log((2500).toLocaleString('en-US'{style:'货币',货币:'美元',})); /* $2,500.00 */
关于浏览器支持和Node.js的一些说明
如今,浏览器支持已不再是一个问题,全球98%的支持率,美国99%,欧盟99%以上有一个垫片可以在僵化的浏览器(如Internet Explorer 8)上支持它,如果你真的需要v13之前的Node.js只支持开箱即用的en-US。一种解决方案是安装完整的icu,请参阅此处了解更多信息查看CanIUse了解更多信息
其他回答
下面是Patrick Desjardins(别名Daok)代码,添加了一些注释和一些小改动:
/*
decimal_sep: character used as decimal separator, it defaults to '.' when omitted
thousands_sep: char used as thousands separator, it defaults to ',' when omitted
*/
Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep)
{
var n = this,
c = isNaN(decimals) ? 2 : Math.abs(decimals), // If decimal is zero we must take it. It means the user does not want to show any decimal
d = decimal_sep || '.', // If no decimal separator is passed, we use the dot as default decimal separator (we MUST use a decimal separator)
/*
According to [https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]
the fastest way to check for not defined parameter is to use typeof value === 'undefined'
rather than doing value === undefined.
*/
t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, // If you don't want to use a thousands separator you can pass empty string as thousands_sep value
sign = (n < 0) ? '-' : '',
// Extracting the absolute value of the integer part of the number and converting to string
i = parseInt(n = Math.abs(n).toFixed(c)) + '',
j = ((j = i.length) > 3) ? j % 3 : 0;
return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
}
这里有一些测试:
// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)
alert(123456789.67392.toMoney() + '\n' + 123456789.67392.toMoney(3) + '\n' + 123456789.67392.toMoney(0) + '\n' + (123456).toMoney() + '\n' + (123456).toMoney(0) + '\n' + 89.67392.toMoney() + '\n' + (89).toMoney());
// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)
alert((-123456789.67392).toMoney() + '\n' + (-123456789.67392).toMoney(-3));
次要变化包括:
移动了一点Math.abs(小数),只有当不是NaN时才能执行。decimal_sep不能再是空字符串(必须使用某种十进制分隔符)我们使用typeof thousand_sep===“undefined”,如How best to determine if a argument is not send to JavaScript function中所建议的不需要(+n||0),因为这是Number对象
JSFiddle公司
我主要基于VisionN的回答:
function format (val) {
val = (+val).toLocaleString();
val = (+val).toFixed(2);
val += "";
return val.replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1" + format.thousands);
}
(function (isUS) {
format.decimal = isUS ? "." : ",";
format.thousands = isUS ? "," : ".";
}(("" + (+(0.00).toLocaleString()).toFixed(2)).indexOf(".") > 0));
我用输入进行了测试:
[ ""
, "1"
, "12"
, "123"
, "1234"
, "12345"
, "123456"
, "1234567"
, "12345678"
, "123456789"
, "1234567890"
, ".12"
, "1.12"
, "12.12"
, "123.12"
, "1234.12"
, "12345.12"
, "123456.12"
, "1234567.12"
, "12345678.12"
, "123456789.12"
, "1234567890.12"
, "1234567890.123"
, "1234567890.125"
].forEach(function (item) {
console.log(format(item));
});
得到了这些结果:
0.00
1.00
12.00
123.00
1,234.00
12,345.00
123,456.00
1,234,567.00
12,345,678.00
123,456,789.00
1,234,567,890.00
0.12
1.12
12.12
123.12
1,234.12
12,345.12
123,456.12
1,234,567.12
12,345,678.12
123,456,789.12
1,234,567,890.12
1,234,567,890.12
1,234,567,890.13
只是为了好玩。
这是另一个尝试,只是为了好玩:
function formatDollar(num) {
var p = num.toFixed(2).split(".");
return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
return num + (num != "-" && i && !(i % 3) ? "," : "") + acc;
}, "") + "." + p[1];
}
还有一些测试:
formatDollar(45664544.23423) // "$45,664,544.23"
formatDollar(45) // "$45.00"
formatDollar(123) // "$123.00"
formatDollar(7824) // "$7,824.00"
formatDollar(1) // "$1.00"
formatDollar(-1345) // "$-1,345.00
formatDollar(-3) // "$-3.00"
一种仅满足原始要求的极简方法:
function formatMoney(n) {
return "$ " + (Math.round(n * 100) / 100).toLocaleString();
}
@丹尼尔·马格廖拉:你说得对。以上是一个仓促而不完整的实施。以下是正确的实施方式:
function formatMoney(n) {
return "$ " + n.toLocaleString().split(".")[0] + "."
+ n.toFixed(2).split(".")[1];
}
我喜欢VisionN的最短答案,除非我需要修改一个没有小数点的数字(123美元而不是123.00美元)。它不起作用,所以我需要破解JavaScript正则表达式的神秘语法,而不是快速复制/粘贴。
这是最初的解决方案
n.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
我会再延长一点:
var re = /\d(?=(\d{3})+\.)/g;
var subst = '$&,';
n.toFixed(2).replace(re, subst);
此处的re部分(字符串替换中的搜索部分)表示
查找所有数字(\d)后跟(?=…)(展望)一个或多个组(…)+正好三位数(\d{3})以点(\.)结尾对所有事件执行此操作(g)
这里的子部分是指:
每次有匹配项时,将其替换为自身($&),后跟逗号。
当我们使用string.replace时,字符串中的所有其他文本保持不变,只有找到的数字(后面跟着3、6、9等其他数字的数字)才会得到一个额外的逗号。
因此,在数字1234567.89中,数字1和4满足条件(1234567.89),并被替换为“1”和“4”,从而得到1234567.89。
如果我们根本不需要美元金额的小数点(即123美元而不是123.00美元),我们可以这样更改正则表达式:
var re2 = /\d(?=(\d{3})+$)/g;
它依赖于行尾($)而不是点(\.),最后的表达式将是(请注意Fixed(0)):
n.toFixed(0).replace(/\d(?=(\d{3})+$)/g, '$&,');
此表达式将给出
1234567.89 -> 1,234,567
此外,您也可以选择单词边界(\b),而不是上面正则表达式中的行尾($)。
如果我误解了正则表达式处理的任何部分,我会提前道歉。