JS

FORMAT NUMBER AS CURRENCY IN JAVASCRIPT

NUMBER TO FORMAT var amount = 123456;

NUMBER FORMAT

01

TO USD - $123,456.00 var usd = new Intl.NumberFormat(   "en-US",  { style: "currency",   currency: "USD"})  .format(amount);

REGULAR EXPRESSION

02

FORMAT TO CURRENCY FUNCTION function tocur (amount) {   return "$" + amount     .toString()     .replace(/\B(?=(\d{3})+(?!\d))/g, ","); }

FORMAT NUMBER - $123,456.78 var demo = tocur(123456.78);

MANUAL FORMAT (A)

03

NUMBER var amount = 123456.78; NUMBER TO STRING amount = amount.toString(), dec = ".00"; EXTRACT DECIMALS var temp = amount.indexOf("."); if (temp != -1) {   dec = amount.substring(temp);   amount = amount.substring     (0, temp); }

MANUAL FORMAT (B)

03

THOUSANDS SEPARATOR if (amount.length>3) {   temp = ""; var j = 0;   for (var i=amount.length-1; i>=0; i--) {     temp = amount[i] + temp;     j++;     if (j%3==0 && i!=0)       { temp = "," + temp; }   }   amount = temp; } RESULT - $123,456.78 amount =  "$" + amount + dec;