6
Apr

Thousand Separator in JavaScript

   Posted by: Grumelo   in javascript

How to render such a number -9,521,654.35 in JavaScript ?

Requirements

  • Number can be negative
  • Number can have or not decimals
  • Separator may change in different countries
  • Solution must be JSLint certified (because that the right way of coding)
  • Solution should not alter existing prototype (because this really not a good idea)
  • Solution must be cross browser compatible

The solution

A very simple function base on RegExp, here it is:

/*
* thousandSeparator (NUMBER n, STRING separator) STRING
* or
* thousandSeparator (String n, STRING sep) STRING
*
* Convert a number to the format xxx,xxx,xxx.xxxx
* Accepts integers, floating point or string
*
* Does not accept exponential notation, etc.
*
* n – the number to be formatted
* sep – the separator character. if skipped, “,” is used
*/

function thousandSeparator(n,sep) {
var sRegExp = new RegExp(‘(-?[0-9]+)([0-9]{3})’),
sValue=n+”;

if (sep === undefined) {sep=’,';}
while(sRegExp.test(sValue)) {
sValue = sValue.replace(sRegExp, ‘$1′+sep+’$2′);
}
return sValue;
}

Examples

thousandSeparator(5000)           => 5,000
thousandSeparator(-5000000)       => -5,000,000
thousandSeparator(5000000.125)    => 5,000,000.125
thousandSeparator(5000000.125,’\”)  => 5’000’000.125

Other solutions

There are many other kind of solution based on Math.foor, split of string, etc
These solutions are heavier than the RegExp solution and require much more lines of codes.

References

Evaluation: Pas terribleAssez bienBienSuper!Excellent! (Pas de votes)
Loading ... Loading ...

Tags: , , , , ,

This entry was posted on Monday, April 6th, 2009 at 15:35 and is filed under javascript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 comments so far

 1 

Hi!

Thanks for this code, I’m using it curerntly and it works fine :) .

The only tring I changed is: sValue=n+”; to sValue=n+”";

January 24th, 2010 at 21:07
Stuart
 2 

As far as I can see, it does not work if there are more than 3 decimal places in the number when using German European format.
1234345.345545 is converted to
1.234.345,345.545

November 30th, 2010 at 16:43

One Trackback/Ping

  1. Javascript: Inserting Thousand Separators | Webdesgin    Aug 04 2010 / 1pm:

    [...] came across this very simple function base on RegExp. Source 0 1 2 3 4 5 6 7 8 9 function thousandSeparator(n,sep) { var sRegExp = new [...]

Leave a reply

Name (*)
Mail (will not be published) (*)
URI
Comment