homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

Thousands separator
for Javascript numbers...

 4:33 pm on Oct 11, 2001 (gmt 0)

take the following variables (numbers -> strings)


Does anybody have a handy function that will convert them to thousand separated, like so?


I've had a crack at this but my code just seems to be getting way overcomplicated (oh, and it doesn't work).



 6:24 pm on Oct 11, 2001 (gmt 0)

I don't remember javascript syntax well, but how 'bout an algorithm:

given string n which is your number and assumming:

loop through the characters in n to find the first occurence of the '.' character. Record it's index in n.

If you dont find it, set the index to be the length of n

starting from the front of n, use the mod 3 of the index of the '.' minus index of the current character to determine if a comma should be inserted behind it. loop through n until you reach the '.' character.


 8:04 am on Oct 12, 2001 (gmt 0)

I started writing a good old algo' but it ended up going on forever - then a colleague mentioned regular expressions to me.

I took a book home and read up on them... it does make life a lot easier:

function addCommas( sValue )
var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');

while(sRegExp.test(sValue)) {
sValue = sValue.replace(sRegExp, '$1,$2');
return sValue;

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved