我想用JavaScript格式化价格.
我想要一个函数,它接受一个float参数并返回如下string格式:
"$ 2,500.00"
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?
是否有内置的JavaScript函数将字符串转换为特定的语言环境(在我的情况下是欧元)?
例如50.00应该转换为50,00 €.
我有一个脚本,我传给它一个字符串,它将返回格式为美元的字符串.因此,如果我发送它"10000"它将返回"$ 10,000.00"现在的问题是,当我发送它"1000000"(100万美元)时,它返回"$ 1,000.00",因为它只设置为基于一组零进行解析.这是我的脚本,如何调整它以占两组零(100万美元)?
String.prototype.formatMoney = function(places, symbol, thousand, decimal) {
if((this).match(/^\$/) && (this).indexOf(',') != -1 && (this).indexOf('.') != -1) {
return this;
}
places = !isNaN(places = Math.abs(places)) ? places : 2;
symbol = symbol !== undefined ? symbol : "$";
thousand = thousand || ",";
decimal = decimal || ".";
var number = Number(((this).replace('$','')).replace(',','')),
negative = number < 0 ? "-" : "",
i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
j = (j = i.length) > …Run Code Online (Sandbox Code Playgroud)