0

I have a script where I pass it a string, and it'll return that string formatted as dollars. So if I send it "10000" it'll return "$10,000.00" Now the problem is that when I send it "1000000" ($1 million) it returns "$1,000.00" because it's only setup to parse based on one set of zeros. Here's my script, how can I adjust it to account for two sets of zeros ($1 million) ??

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) : ""); };

Thanks in advance for any useful information!

Anthony Cordio
  • 57
  • 1
  • 1
  • 8

2 Answers2

22
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
Domenic
  • 110,262
  • 41
  • 219
  • 271
  • To my surprise, Javascript doesn't have a currency sign for my country's currency code as a result it throughs an error or returns the wrong sign. I think this solution below is more generic hence you can add any currency sign using HTML const price = 1470000.15; let formatMoney= Intl.NumberFormat('en-IN'); console.log("US Locale output: " + formatMoney.format(price)); – Solomon Sunday Nov 02 '21 at 08:27
1

Give this a shot it looks for a decimal separator but you can remove that part if youd like:

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

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

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

// return newNum if youd like
 };
Nicole Phillips
  • 753
  • 1
  • 18
  • 41