JS

HOW TO ADD COMMAS TO NUMBERS IN JAVASCRIPT

THE NUMBER var num = 1234567.89;

TO LOCALE STRING

01

// ¥1,234,568 var loc = num.toLocaleString("ja-JP", { style: "currency", currency: "JPY" });

TO LOCALE STRING // 1,234,567.89 var loc = num.toLocaleString("en-US");

THE NUMBER var num = 1234567.89;

REGULAR EXPRESSION

02

INSERT COMMAS - 1,234,567.89 commas = replace(/\B(?=(\d{3})+(?!\d))/g, ",");

CONVERT TO STRING var commas = num.toString();

NUMBER TO STRING var num = 12345.78; num = num.toString(), dec = ".00", dot = num.indexOf(".");

MANUAL FORMAT (A)

03

EXTRACT DECIMALS (IF ANY) if (dot != -1) {   dec = +("0" + num.substring(dot));   dec = dec.toFixed(2).toString()              .substring(1);   num = num.substring(0, dot);  }

ADD THOUSAND SEPARATORS if (num.length>3) {   let temp = "", j = 0;   for (let i=num.length-1; i>=0; i--) {     temp = num[i] + temp; j++;     if (j%3==0 && i!=0) { temp = ","+temp; }   }   num = temp;  }

MANUAL FORMAT (B)

04

RESULT - 12,345.78 num = num + dec;