Welcome to WebmasterWorld Guest from 54.166.114.43

Forum Moderators: open

Message Too Old, No Replies

Thousands separator

for Javascript numbers...

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

WebmasterWorld Senior Member 10+ Year Member



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).

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

WebmasterWorld Senior Member 10+ Year Member



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)

WebmasterWorld Senior Member 10+ Year Member



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;
}

 

Featured Threads

Hot Threads This Week

Hot Threads This Month