Number Formatting with AS3

I ran into a problem the other day where, I’m pretty sure a lot of you actually ran into as well, number formatting with AS3.

The big problem is that Math.round doesn’t allow you to specify a precision.

I tried to make this function work as closely as PHP’s number_format() function, here’s my attempt:

function numberFormat(num:Number, decimals:int = 0, thousands:String = ','):String
{
	var buffer:String = '';
	var truncate:Number = 0;
	var orig:String = '';
	if (decimals > 0) {
		var ratio:int = Math.pow(10, decimals);
		var tempDecimal:Number = (Math.round(num * ratio) / ratio);
		truncate = (Math.round((tempDecimal - Math.floor(num)) * ratio) / ratio);
		if (truncate == 1) {
			num += 1;
			truncate = 0;
		}
		orig = Math.floor(num).toString();
	}
	else {
		orig = Math.round(num).toString();
	}

	var iteration:int = 0;

	for (var i = (orig.length - 1); i >= 0; i--) {
		if (((iteration % 3) == 0) && (iteration > 0)) {
			buffer = thousands + buffer;
		}
		buffer = orig.charAt(i) + buffer;
		iteration++;
	}

	if (truncate > 0) {
		buffer += '.' + truncate.toString().substr(2);
	}

	return buffer;
}

Hopefully, it helps you resolve your number formatting issues.

Leave a Reply

*