如何在JavaScript中将数字格式设置为美元货币字符串? [英] How can I format numbers as dollars currency string in JavaScript?
问题描述
我想用JavaScript格式化一个价格。
我想要一个以 float
作为参数的函数,并返回一个<
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' / code>
执行此操作的最佳方法是什么?
var profits = 2489.8237
profit.toFixed(3)/ /返回2489.824(凑整)
profit.toFixed(2)//返回2489.82
profit.toFixed(7)//返回2489.8237000(填充)
然后您可以添加'$'的符号。
如果您需要','您可以使用的数千元:
$ p $ Number.prototype.formatMoney = function(c,d,t){
var n = this,
c = isNaN(c = Math.abs(c))? 2:c,
d = d == undefined? :d,
t = t == undefined? ,:t,
s = n < 0? - :
i = String(parseInt(n = Math.abs(Number(n)|| 0).toFixed(c))),
j =(j = i.length) > 3? j%3:0;
return s +(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):);
};
和它一起使用:
<$ p $ (123456789.12345).formatMoney(2,'。',',');
如果您总是使用'。'和',',您可以将它们关闭你的方法调用,方法会默认为你。
(123456789.12345).formatMoney(2);
如果您的文化有两个符号翻转(即欧洲人),只需粘贴以下两行 formatMoney
方法:
d = d == undefined? ,:d,
t = t == undefined? :t,
I would like to format a price in JavaScript.
I'd like a function which takes a float
as an argument and returns a string
formatted like this:
"$ 2,500.00"
What's the best way to do this?
You can use:
var profits=2489.8237
profits.toFixed(3) //returns 2489.824 (round up)
profits.toFixed(2) //returns 2489.82
profits.toFixed(7) //returns 2489.8237000 (padding)
Then you can add the sign of '$'.
If you require ',' for thousand you can use:
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))),
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (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) : "");
};
And use it with:
(123456789.12345).formatMoney(2, '.', ',');
If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you.
(123456789.12345).formatMoney(2);
If your culture has the two symbols flipped (i.e. Europeans), just paste over the following two lines in the formatMoney
method:
d = d == undefined ? "," : d,
t = t == undefined ? "." : t,
这篇关于如何在JavaScript中将数字格式设置为美元货币字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!