我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
当前回答
以下内容简洁易懂,不依赖任何过于复杂的正则表达式。
函数moneyFormat(价格,符号=“$”){const pieces=parseFloat(price).toFixed(2).split(“”)设ii=件长度-3而((ii-=3)>0){拼接件(ii,0,',')}return符号+pieces.join(“”)}控制台日志(money格式(100),money格式(1000),货币格式(10000.00),货币格式(1000000000000000000))
这是一个在最终输出中具有更多选项的版本,允许以不同的位置格式格式化不同的货币。
//高阶函数,接受期权,然后返回价格,并返回格式化的价格常量makeMoneyFormatter=({符号=“$”,分隔符=',',十进制='.',append=false,精度=2,round=真,风俗}={})=>值=>{常量=[1,10,100,1000,10000,100000,1000000,10000000]值=圆形? (数学舍入(值*e[precision])/e[precisity]):parseFloat(值)常量件=值.to固定(精度).replace('.',十进制).split(“”)设ii=工件长度-(精度?精度+1:0)而((ii-=3)>0){件.拼接(ii,0,分隔符)}if(自定义类型==“函数”){返回自定义项({签名float:值,值:pieces.join(“”)})}返回追加? pieces.join(“”)+符号:sign+pieces.join(“”)}//使用正确的格式选项创建货币转换器const formatDollar=makeMoneyFormatter()const formatPound=makeMoneyFormatter({符号:“£”,精度:0})const formatEuro=makeMoneyFormatter({符号:“€”,分隔符:“.”,十进制:',',附加:真})const customFormat=makeMoneyFormatter({圆形:假,custom:({value,float,sign})=>`SALE:$${value}USD`})控制台日志(格式磅(1000),格式美元(10000.0066),格式欧元(1000000.00),自定义格式(999999.555))
其他回答
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了解更多信息
+1向Jonathan M提供原始方法。由于这是一个明确的货币格式化程序,我继续在输出中添加了货币符号(默认为“$”),并添加了一个默认逗号作为千位分隔符。如果您实际上不需要货币符号(或千位分隔符),只需使用“”(空字符串)作为它的参数。
Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator, currencySymbol) {
// check the args and supply defaults:
decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;
decSeparator = decSeparator == undefined ? "." : decSeparator;
thouSeparator = thouSeparator == undefined ? "," : thouSeparator;
currencySymbol = currencySymbol == undefined ? "$" : currencySymbol;
var n = this,
sign = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return sign + currencySymbol + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};
PatrickDesjardins的回答看起来不错,但我更喜欢简单的JavaScript代码。下面是我刚刚编写的一个函数,用于输入一个数字并以货币格式返回(减去美元符号):
// Format numbers to two decimals with commas
function formatDollar(num) {
var p = num.toFixed(2).split(".");
var chars = p[0].split("").reverse();
var newstr = '';
var count = 0;
for (x in chars) {
count++;
if(count%3 == 1 && count != 1) {
newstr = chars[x] + ',' + newstr;
} else {
newstr = chars[x] + newstr;
}
}
return newstr + "." + p[1];
}
一个简单的选项,通过先反转字符串和基本正则表达式来正确放置逗号。
String.prototype.reverse = function() {
return this.split('').reverse().join('');
};
Number.prototype.toCurrency = function( round_decimal /*boolean*/ ) {
// format decimal or round to nearest integer
var n = this.toFixed( round_decimal ? 0 : 2 );
// convert to a string, add commas every 3 digits from left to right
// by reversing string
return (n + '').reverse().replace( /(\d{3})(?=\d)/g, '$1,' ).reverse();
};
这里是我见过的最好的JavaScript货币格式化程序:
Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {
var n = this,
decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
decSeparator = decSeparator == undefined ? "." : decSeparator,
thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
sign = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};
它被重新格式化并从这里借用:如何将数字格式化为货币字符串
您必须提供您自己的货币代号(您使用了$以上)。
这样调用它(尽管注意,参数默认为2、逗号和句点,因此如果这是您的首选,则不需要提供任何参数):
var myMoney = 3543.75873;
var formattedMoney = '$' + myMoney.formatMoney(2, ',', '.'); // "$3,543.76"