Posts Tagged ‘comma

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