我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
当前回答
以下是将数字转换为货币格式的简短最佳方法:
function toCurrency(amount){
return amount.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
// usage: toCurrency(3939920.3030);
其他回答
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];
}
这里有一些解决方案,都通过了测试套件。包括测试套件和基准测试。如果你想复制和粘贴来测试,试试这个要点。
方法0(RegExp)
它是基于VisioN的答案,但如果没有小数点,它会修复。
if (typeof Number.prototype.format === 'undefined') {
Number.prototype.format = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.');
a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '$&,');
return a.join('.');
}
}
方法1
if (typeof Number.prototype.format === 'undefined') {
Number.prototype.format = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.'),
// Skip the '-' sign
head = Number(this < 0);
// Skip the digits that's before the first thousands separator
head += (a[0].length - head) % 3 || 3;
a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',$&');
return a.join('.');
};
}
方法2(拆分到阵列)
if (typeof Number.prototype.format === 'undefined') {
Number.prototype.format = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.');
a[0] = a[0]
.split('').reverse().join('')
.replace(/\d{3}(?=\d)/g, '$&,')
.split('').reverse().join('');
return a.join('.');
};
}
方法3(循环)
if (typeof Number.prototype.format === 'undefined') {
Number.prototype.format = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('');
a.push('.');
var i = a.indexOf('.') - 3;
while (i > 0 && a[i-1] !== '-') {
a.splice(i, 0, ',');
i -= 3;
}
a.pop();
return a.join('');
};
}
用法示例
console.log('======== Demo ========')
console.log(
(1234567).format(0),
(1234.56).format(2),
(-1234.56).format(0)
);
var n = 0;
for (var i=1; i<20; i++) {
n = (n * 10) + (i % 10)/100;
console.log(n.format(2), (-n).format(2));
}
分离器
如果我们需要自定义千位分隔符或小数分隔符,请使用replace():
123456.78.format(2).replace(',', ' ').replace('.', ' ');
测试套件
function assertEqual(a, b) {
if (a !== b) {
throw a + ' !== ' + b;
}
}
function test(format_function) {
console.log(format_function);
assertEqual('NaN', format_function.call(NaN, 0))
assertEqual('Infinity', format_function.call(Infinity, 0))
assertEqual('-Infinity', format_function.call(-Infinity, 0))
assertEqual('0', format_function.call(0, 0))
assertEqual('0.00', format_function.call(0, 2))
assertEqual('1', format_function.call(1, 0))
assertEqual('-1', format_function.call(-1, 0))
// Decimal padding
assertEqual('1.00', format_function.call(1, 2))
assertEqual('-1.00', format_function.call(-1, 2))
// Decimal rounding
assertEqual('0.12', format_function.call(0.123456, 2))
assertEqual('0.1235', format_function.call(0.123456, 4))
assertEqual('-0.12', format_function.call(-0.123456, 2))
assertEqual('-0.1235', format_function.call(-0.123456, 4))
// Thousands separator
assertEqual('1,234', format_function.call(1234.123456, 0))
assertEqual('12,345', format_function.call(12345.123456, 0))
assertEqual('123,456', format_function.call(123456.123456, 0))
assertEqual('1,234,567', format_function.call(1234567.123456, 0))
assertEqual('12,345,678', format_function.call(12345678.123456, 0))
assertEqual('123,456,789', format_function.call(123456789.123456, 0))
assertEqual('-1,234', format_function.call(-1234.123456, 0))
assertEqual('-12,345', format_function.call(-12345.123456, 0))
assertEqual('-123,456', format_function.call(-123456.123456, 0))
assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))
// Thousands separator and decimal
assertEqual('1,234.12', format_function.call(1234.123456, 2))
assertEqual('12,345.12', format_function.call(12345.123456, 2))
assertEqual('123,456.12', format_function.call(123456.123456, 2))
assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}
console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);
基准
function benchmark(f) {
var start = new Date().getTime();
f();
return new Date().getTime() - start;
}
function benchmark_format(f) {
console.log(f);
time = benchmark(function () {
for (var i = 0; i < 100000; i++) {
f.call(123456789, 0);
f.call(123456789, 2);
}
});
console.log(time.format(0) + 'ms');
}
// If not using async, the browser will stop responding while running.
// This will create a new thread to benchmark
async = [];
function next() {
setTimeout(function () {
f = async.shift();
f && f();
next();
}, 10);
}
console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
next();
在将PHP number_format()转换为javascript之后,这对我很有用
function number_format(number, decimals = 0, dec_point = ".",thousands_sep = ",") {
number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
s = '',
toFixedFix = function(n, prec)
{
var k = Math.pow(10, prec);
return '' + (Math.round(n * k) / k).toFixed(prec);
};
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' +
Math.round(n)).split('.');
if (s[0].length > 3)
{
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,
thousands_sep);
}
if ((s[1] || '').length < prec)
{
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec_point);
}
这里是我见过的最好的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"
数字.原型.固定
此解决方案与每个主要浏览器都兼容:
const profits = 2489.8237;
profits.toFixed(3) // Returns 2489.824 (rounds up)
profits.toFixed(2) // Returns 2489.82
profits.toFixed(7) // Returns 2489.8237000 (pads the decimals)
您只需添加货币符号(例如“$”+利润.toFixed(2)),即可获得美元金额。
自定义函数
如果需要在每个数字之间使用,则可以使用此函数:
函数格式Money(number,decPlaces,decSep,thouSep){decPlaces=isNaN(decPlaces=数学.abs(decPlaces))?2:decPlaces,decSep=decSep的类型==“未定义”?“.”:12月9日;thouSep=thouSep==“未定义”的类型?“,”:thouSep;var符号=数字<0?"-" : "";var i=字符串(parseInt(number=Math.abs(number(number)||0).toFixed(decPlaces)));变量j=(j=i.length)>3?j%3:0;返回标志+(j?i.substr(0,j)+thouSep:“”)+i.substr(j).replace(/(\decSep{3})(?=\decSep)/g,“$1”+thouSep)+(decPlaces?decSep+Math.abs(数字-i).toFixed(decPlace).slice(2):“”);}document.getElementById(“b”).addEventListener(“单击”,event=>{document.getElementById(“x”).innerText=“结果为:”+formatMoney(document.getElement ById(”d“).value);});<label>插入您的金额:<input id=“d”type=“text”placeholder=“Cash amount”/></label><br/><button id=“b”>获取输出</button><p id=“x”>(按下按钮获取输出)</p>
这样使用:
(123456789.12345).formatMoney(2, ".", ",");
如果你总是使用“.”和',',您可以将它们从方法调用中删除,方法将为您默认它们。
(123456789.12345).formatMoney(2);
如果您的文化中有两个符号翻转(即,欧洲人),并且您希望使用默认值,只需在formatMoney方法中粘贴以下两行:
d = d == undefined ? "," : d,
t = t == undefined ? "." : t,
自定义功能(ES6)
如果您可以使用现代ECMAScript语法(即,通过Babel),则可以使用更简单的函数:
函数formatMoney(amount,decimalCount=2,decimal=“.”,千=“,”){尝试{decimalCount=数学.abs(decimalCount);decimalCount=isNaN(decimalCount)?2:小数计数;常量负符号=金额<0?"-" : "";让i=parseInt(amount=Math.abs(Number(amount)||0).toFixed(decimalCount)).toString();设j=(i.length>3)?i.长度%3:0;回来否定符号+(j?i.substr(0,j)+千:“”)+i.substr(j).replace(/(\d{3})(?=\d)/g,“$1”+千)+(decimalCount?decimal+Math.abs(amount-i).toFixed(decimalCount).slice(2):“”);}捕获(e){控制台日志(e)}};document.getElementById(“b”).addEventListener(“单击”,event=>{document.getElementById(“x”).innerText=“结果为:”+formatMoney(document.getElement ById(”d“).value);});<label>插入您的金额:<input id=“d”type=“text”placeholder=“Cash amount”/></label><br/><button id=“b”>获取输出</button><p id=“x”>(按下按钮获取输出)</p>