Follow @shai_rai
Many times when you write a number in your site you want to add commas and format the number, for example: instead of 1000000 I want to my user to see 1,000,000.
Using JavaScript this is very simple task, you can also extend this code example to a Plugin inside JavaScript Lib - How To Write JavaScript \ JQuery Plugins
First I’m looking for . char inside the number (we don’t want to split this…) and after that using Regex just adding comma after 3 chars.
function addCommas(nStr) { nStr += ''; var x = nStr.split('.'); var x1 = x[0]; var x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2;}
Example:
addCommas(1000000);// 1,000,000 addCommas(1234.1111);// 1,234.1111 addCommas('9999999.1234');// 9,999,999.1234 addCommas(-500000.00);// -500,000.00
Pingback from Javascript tonumber | Zerafoto