Inserting commas into numbers (SOLVED)

Subscribe to Inserting commas into numbers (SOLVED) 3 posts

avatar for DrYoshiyahu DrYoshiyahu 678 posts
Flag Post

I’d like to have commas every three digits in my score display to make it easier to read. I had this problem once before, in my AS2 days, and I solved it by seperating each digit of the number and then arranging the number like so:

ten thousands digit, thousands digit, comma, hundreds digit, tens digit, ones digit.

Obviously that’s a lot of excessive code.

I know that I can turn my score to a string, work out how many characters there are in the string, and then insert the comma in between characters 2 and 3 for example.

But I don’t know what the functions are that I need to use. Can someone please tell me what they are?
-Yoshiyahu

PS. Unless someone already has an algorithm I can steal that calculates it for me, without an if statement for every possible number of digits.

 
avatar for skyboy skyboy 6261 posts
Flag Post

this issue came up many years ago, i and another programmer got into a performance war over it and this was my final result:

		final protected function numberDelimiter2(num:Number, decimalPrecision:int = 0, delimiter:String = ",", charGroup:uint = 3):String {
			var d:String = num.toFixed(decimalPrecision);
			if (int(charGroup == 0) | charGroup >> 31) return d;
			var n:int = int(num < 0), len:int = d.length - n - (decimalPrecision + int(decimalPrecision > 0));
			if (len <= charGroup) return d;
			if (len % charGroup) {
				var c:int = n + len % charGroup, o:String = d.substring(0, c);
				while (~(((len -= charGroup) >> 31))) {
					o = o + delimiter + d.substring(c, c += charGroup);
				}
				return o + d.substring(c);
			}
			var count:int = n + charGroup, out:String = d.substring(0, count);
			while (len -= charGroup) {
				out = out + delimiter + d.substring(count, count += charGroup);
			}
			return out + d.substring(count);
		}

i could improve its performance substantially by using a ByteArray, but it won’t be used often enough to warrant that

 
avatar for DrYoshiyahu DrYoshiyahu 678 posts
Flag Post

Thanks again mate, works perfectly!