31
Mar
09

[Javascript] Number Format String (1)

Ive been set a mission to make 3, different, functions to format a number with commas, e.g. 12345 = 12,345; 1234567890 = 1,234,567,890

Here is number one:

function numberFormat_1(text) {
	//Reverse string
	//Loop through adding every character
	//If index = 3, add a comma
	//Reverse string
	text = text.split("").reverse().join("");
	var output = "";
	var j=0;
	for(var i = 0;i<text.length;i++) {
		output += text.charAt(i);
		j++;
		if(j==3 && i != text.length-1) {
			output += ",";
			j=0;
		}
	}
	output = output.split("").reverse().join("");
	return output;
}

Usage:

	var text = "123456789123456789";
	text = numberFormat_1(text);
	alert(text);

Would Output:

123,456,789,123,456,789

Advertisements

0 Responses to “[Javascript] Number Format String (1)”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: