Format an Integer Number with Commas

Turn 1000 into 1,000.

Here’s a little snippet I needed to write to format an integer with commas. You’ll use it all the time in high scores. It’s a standalone utility function. Save it in a file named “formatNumber.as”.
Note: this function does not format decimal and float numbers. Just positive integers.
The reason it won’t work with those is the modulus operator “%” is essentially counting backwards from the end of the number-as-a-string to know where to insert a comma.

package util 
{
	/**
	 * formats an integer with commas
	 * Example: input 1000000, output 1,000,000
	 * @author PlasticSturgeon
	 */
	public function formatNumber(value:int):String 
	{
		var vt:String = _votes.toString();
		var count:int = (vt.length - 1) % 3;
		var formatted:String = "";
		for (var i:int = 0; i < vt.length; i++) 
		{
			formatted += vt.substr(i, 1);
			if ((i - count) % 3 == 0 && (i+1) != vt.length) {
				formatted += ",";
			}			
		}
		return formatted;
	}
}

Enjoy!

About The Plastic Sturgeon

This is my site. It gets pretty biographical on the About page.
This entry was posted in Code Snippets. Bookmark the permalink.

One Response to Format an Integer Number with Commas

  1. Pingback: Format An Int With Commas | NNGAFOOK.com | Blog

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>