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!

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