...

# Inserting (000) separators into numbers displayed as string variables

Dieter Rausch
01-11-2004, 02:13 PM
Hi everyone,

Is there a function in Javascript that will take a number, convert it to a string and insert a user defined separator at every third digit to the left of the decimal point? It should also handle negative values. A currency symbol is not essential. I have written an experimental script for whole numbers which does what I want, but perhaps there is a more efficient way to do this. Here is my code.

var num=19555;
sepType=",";
var y= num;
str = new String(y);
if (str.substr(0,1)=="-"){ //Check if number is -ve
var negNo = true;
str=str.substr(1,str.length-1); //Assign number without -ve sign to a variable
}
var strLength = str.length;
var noOfSeps= Math.floor((strLength-1)/3); //Determine the no. of separators required
var x=0;
var y=(strLength-noOfSeps*3); //Determines no. of digits before the first separator position
if (negNo== true)
document.write("-");

for (i = 0; i <= noOfSeps; i++)
{
document.write(str.substr(x,y));
if (i < noOfSeps){
document.write(sepType); //Write number up to first separator
}
if (x == 0){ // Determines the initial no. of digits and increments var's x and y accordingly
}
if (y < 3){
var x = (x+y);
var y = 3;
}
else {
var x = x + 3;
}
}
As I said it works, but cannot handle floating point numbers or currency symbols in its current format, but this is not required. I had a similar problem recently, where many lines of code where evently replaced by a single line of code - i.e. 12.325794.toFixed(2) == "12.33" posted by jkd.
Is there perhaps a similar built-in function which would be applicable to my case?

Incidently, I did a number of searches looking for .toFixed() and num.toFixed() and found nothing. Is there a site that provides examples and more info on this.

Any help will be appreciated.

Dieter