0
我有一个脚本,我将它传递给一个字符串,并且它将返回格式为美元的字符串。所以,如果我发送它“10000”它将返回“$ 10,000.00”现在的问题是,当我发送它“1000000”(100万美元)它返回“$ 1,000.00”,因为它只设置为基于一组零。这是我的脚本,我如何调整它以计算两套零(100万美元)?Javascript函数格式化为货币
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) > 3 ? j % 3 : 0;
return negative + symbol + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : ""); };
在此先感谢您提供任何有用信息!
使用循环。无论何时您需要重复代码,请使用循环。 – Carcigenicate
总的来说:这是一个很常见的事情,可能存在您应该使用的API或库,而不是重新创建这个特定的轮子。 – deceze