homepage Welcome to WebmasterWorld Guest from 54.242.231.109
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Thousands separator
for Javascript numbers...
joshie76




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

take the following variables (numbers -> strings)

1000.00123
100000
12000000.00

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

1,000.00123
100,000
12,000,000.00

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

 

ggrot




msg:1482632
 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.

joshie76




msg:1482633
 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