2016-11-04 63 views
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) : ""); }; 

在此先感谢您提供任何有用信息!

+0

使用循环。无论何时您需要重复代码,请使用循环。 – Carcigenicate

+0

总的来说:这是一个很常见的事情,可能存在您应该使用的API或库,而不是重新创建这个特定的轮子。 – deceze

回答

3
function formatMoney(number) { 
    return number.toLocaleString('en-US', { style: 'currency', currency: 'USD' }); 
} 

console.log(formatMoney(10000)); // $10,000.00 
console.log(formatMoney(1000000)); // $1,000,000.00 
1

给这个一杆它寻找一个小数点,但如果你几乎可以删除的那部分,如:

\t { 
 
\t number = parseFloat(number); 
 
\t //if number is any one of the following then set it to 0 and return 
 
\t if (isNaN(number)) { 
 
\t  return ('0' + '{!decimalSeparator}' + '00'); 
 
\t } 
 

 
\t number = Math.round(number * 100)/100; //number rounded to 2 decimal places 
 
\t var numberString = number.toString(); 
 
\t numberString = numberString.replace('.', '{!decimalSeparator}'); 
 

 
\t var loc = numberString.lastIndexOf('{!decimalSeparator}'); //getting position of decimal seperator 
 
\t if (loc != -1 && numberString.length - 2 == loc) { 
 
\t  //Adding one 0 to number if it has only one digit after decimal 
 
\t  numberString += '0'; 
 
\t } else if (loc == -1 || loc == 0) { 
 
\t  //Adding a decimal seperator and two 00 if the number does not have a decimal separator 
 
\t  numberString += '{!decimalSeparator}' + '00'; 
 
\t } 
 
\t loc = numberString.lastIndexOf('{!decimalSeparator}'); //getting position of decimal seperator id it is changed after adding 0 
 
\t var newNum = numberString.substr(loc, 3); 
 
\t // Logic to add thousands seperator after every 3 digits 
 
\t var count = 0; 
 
\t for (var i = loc - 1; i >= 0; i--) { 
 
\t  if (count != 0 && count % 3 == 0) { 
 
\t  newNum = numberString.substr(i, 1) + '{!thousandSeparator}' + newNum; 
 
\t  } else { 
 
\t  newNum = numberString.substr(i, 1) + newNum; 
 
\t  } 
 
\t  count++; 
 
\t } 
 

 
// return newNum if youd like 
 
\t };