01
Apr
09

[Javascript] Number Format String (2)

Second one, similar to the last but instead of reversing twice, it builds the string backwards then reverses it.

function numberFormat_2(text) {
	//Loop backwards through the string
	//Add every character
	//If index = 3, add comma
	//Reverse string;
	var i = text.length;
	var output = "";
	var k=0;
	var j=-1;
	while (i > -1) {
		output += text.charAt(i);
		j++;
		if(j==3 && i !=0) {
			output += ",";
			j=0;
		}
		i--;
	}
	output = output.split("").reverse().join("");
	return output
}

Usage:

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

Would Output:

123,456,789,123,456,789

Advertisements

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



  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: