我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
当前回答
使用正则表达式的较短方法(用于插入空格、逗号或点):
Number.prototype.toCurrencyString = function(){
return this.toFixed(2).replace(/(\d)(?=(\d{3})+\b)/g, '$1 ');
}
n = 12345678.9;
alert(n.toCurrencyString());
其他回答
function getMoney(A){
var a = new Number(A);
var b = a.toFixed(2); // Get 12345678.90
a = parseInt(a); // Get 12345678
b = (b-a).toPrecision(2); // Get 0.90
b = parseFloat(b).toFixed(2); // In case we get 0.0, we pad it out to 0.00
a = a.toLocaleString(); // Put in commas - Internet Explorer also puts in .00, so we'll get 12,345,678.00
// If Internet Explorer (our number ends in .00)
if(a < 1 && a.lastIndexOf('.00') == (a.length - 3))
{
a = a.substr(0, a.length-3); // Delete the .00
}
return a + b.substr(1); // Remove the 0 from b, then return a + b = 12,345,678.90
}
alert(getMoney(12345678.9));
这适用于Firefox和Internet Explorer。
这里是我见过的最好的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"
只需使用本机javascript Intl
您只需使用选项设置其值的格式
常量编号=1233445.5678console.log(新的Intl.NumberFormat('en-US',{style:'currency',currency:'USD'}).format(数字));
mozilla文档链接
toLocaleString很好,但它不适用于所有浏览器。我通常使用currencyFormatter.js(https://osrec.github.io/currencyFormatter.js/). 它非常轻量级,包含所有现成的货币和语言环境定义。它还擅长格式化格式异常的货币,如INR(以10万卢比、10万卢比等为单位分组)。此外,没有任何依赖关系!
OSREC.CurrencyFormatter.format(2534234,{currency:'INR'});//退换商品₹ 25,34,234.00
OSREC.CurrencyFormatter.format(2534234,{currency:'EUR'});//退货2.534.234,00欧元
OSREC.CurrencyFormatter.format(2534234,{currency:'EUR',locale:'fr'});//退货2 534 234,00欧元
YUI代码库使用以下格式:
format: function(nData, oConfig) {
oConfig = oConfig || {};
if(!YAHOO.lang.isNumber(nData)) {
nData *= 1;
}
if(YAHOO.lang.isNumber(nData)) {
var sOutput = nData + "";
var sDecimalSeparator = (oConfig.decimalSeparator) ? oConfig.decimalSeparator : ".";
var nDotIndex;
// Manage decimals
if(YAHOO.lang.isNumber(oConfig.decimalPlaces)) {
// Round to the correct decimal place
var nDecimalPlaces = oConfig.decimalPlaces;
var nDecimal = Math.pow(10, nDecimalPlaces);
sOutput = Math.round(nData*nDecimal)/nDecimal + "";
nDotIndex = sOutput.lastIndexOf(".");
if(nDecimalPlaces > 0) {
// Add the decimal separator
if(nDotIndex < 0) {
sOutput += sDecimalSeparator;
nDotIndex = sOutput.length-1;
}
// Replace the "."
else if(sDecimalSeparator !== "."){
sOutput = sOutput.replace(".",sDecimalSeparator);
}
// Add missing zeros
while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) {
sOutput += "0";
}
}
}
// Add the thousands separator
if(oConfig.thousandsSeparator) {
var sThousandsSeparator = oConfig.thousandsSeparator;
nDotIndex = sOutput.lastIndexOf(sDecimalSeparator);
nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length;
var sNewOutput = sOutput.substring(nDotIndex);
var nCount = -1;
for (var i=nDotIndex; i>0; i--) {
nCount++;
if ((nCount%3 === 0) && (i !== nDotIndex)) {
sNewOutput = sThousandsSeparator + sNewOutput;
}
sNewOutput = sOutput.charAt(i-1) + sNewOutput;
}
sOutput = sNewOutput;
}
// Prepend prefix
sOutput = (oConfig.prefix) ? oConfig.prefix + sOutput : sOutput;
// Append suffix
sOutput = (oConfig.suffix) ? sOutput + oConfig.suffix : sOutput;
return sOutput;
}
// Still not a number. Just return it unaltered
else {
return nData;
}
}
它需要编辑,因为YUI库是可配置的,比如用“.”替换oConfig.decimalSeparator。