我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
当前回答
使用regexp的更快方法:
Number.prototype.toMonetaryString = function() {
var n = this.toFixed(2), m;
//var = this.toFixed(2).replace(/\./, ','); For comma separator
// with a space for thousands separator
while ((m = n.replace(/(\d)(\d\d\d)\b/g, '$1 $2')) != n)
n = m;
return m;
}
String.prototype.fromMonetaryToNumber = function(s) {
return this.replace(/[^\d-]+/g, '')/100;
}
其他回答
请尝试以下代码
"250000".replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
答案:250000
因为每个问题都需要单线解决方案:
Number.prototype.formatCurrency = function() { return this.toFixed(2).toString().split(/[-.]/).reverse().reduceRight(function (t, c, i) { return (i == 2) ? '-' + t : (i == 1) ? t + c.replace(/(\d)(?=(\d{3})+$)/g, '$1,') : t + '.' + c; }, '$'); }
这很容易针对不同的地区进行更改。只需将“$1”更改为“$1.”和“.”转换为“”、“”和。以数字表示。可以通过更改末尾的“$”来更改货币符号。
或者,如果您有ES6,您可以使用默认值声明函数:
Number.prototype.formatCurrency = function(thou = ',', dec = '.', sym = '$') { return this.toFixed(2).toString().split(/[-.]/).reverse().reduceRight(function (t, c, i) { return (i == 2) ? '-' + t : (i == 1) ? t + c.replace(/(\d)(?=(\d{3})+$)/g, '$1' + thou) : t + dec + c; }, sym); }
console.log((4215.57).formatCurrency())
$4,215.57
console.log((4216635.57).formatCurrency('.', ','))
$4.216.635,57
console.log((4216635.57).formatCurrency('.', ',', "\u20AC"))
€4.216.635,57
哦,它也适用于负数:
console.log((-6635.574).formatCurrency('.', ',', "\u20AC"))
-€6.635,57
console.log((-1066.507).formatCurrency())
-$1,066.51
当然,你不必有货币符号:
console.log((1234.586).formatCurrency(',','.',''))
1,234.59
console.log((-7890123.456).formatCurrency(',','.',''))
-7,890,123.46
console.log((1237890.456).formatCurrency('.',',',''))
1.237.890,46
适用于所有当前浏览器
使用toLocaleString以货币的语言敏感表示形式格式化货币(使用ISO 4217货币代码)。
(2500).toLocaleString("en-GB", {style: "currency", currency: "GBP", minimumFractionDigits: 2})
avenmore的南非兰特代码片段示例:
console.log((2500).toLocaleString(“en-ZA”,{style:“currency”,currency:“ZAR”,minimumFractionDigits:2}))//->2 500,00兰特console.log((2500).toLocaleString(“en-GB”,{style:“currency”,currency:“ZAR”,minimumFractionDigits:2}))//->2500欧元
我很难找到一个简单的库来处理日期和货币,所以我创建了自己的:https://github.com/dericeira/slimFormatter.js
简单如下:
var number = slimFormatter.currency(2000.54);
我喜欢简单:
function formatPriceUSD(price) {
var strPrice = price.toFixed(2).toString();
var a = strPrice.split('');
if (price > 1000000000)
a.splice(a.length - 12, 0, ',');
if (price > 1000000)
a.splice(a.length - 9, 0, ',');
if (price > 1000)
a.splice(a.length - 6, 0, ',');
return '$' + a.join("");
}