2016-11-04 65 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 };