Return to Snippet

Revision: 11053
at January 22, 2009 03:52 by Mijos


Updated Code
function formatDecimals(num:Number, digits:uint):String
{
	var tenToPower:Number = Math.pow(10, digits);
	var cropped:String = String(Math.round(num * tenToPower) / tenToPower);
			
	var decimalPosition:int;
			
	for (var i:int = 0; i < cropped.length; i++) 
	{
		if (cropped.charAt(i) == ".")
		{
			decimalPosition = i;
		}
	}
			
	var output:String = cropped;
	var decimals:String = cropped.substr(decimalPosition + 1, cropped.length);
	var missingZeros:Number = digits - decimals.length;
			
	if (decimals.length < digits && decimalPosition > 0)
	{
		for (var j:int = 0; j < missingZeros; j++) 
		{
			output += "0";
		}
	}
			
	return output;
}

Revision: 11052
at January 22, 2009 03:48 by Mijos


Initial Code
function formatDecimals(num:Number, digits:uint):String
		{
			var tenToPower:Number = Math.pow(10, digits);
			var cropped:String = String(Math.round(num * tenToPower) / tenToPower);
			
			var decimalPosition:int;
			
			for (var i:int = 0; i < cropped.length; i++) 
			{
				if (cropped.charAt(i) == ".")
				{
					decimalPosition = i;
				}
			}
			
			var output:String = cropped;
			var decimals:String = cropped.substr(decimalPosition + 1, cropped.length);
			var missingZeros:Number = digits - decimals.length;
			
			if (decimals.length < digits && decimalPosition > 0)
			{
				for (var j:int = 0; j < missingZeros; j++) 
				{
					output += "0";
				}
			}
			
			return output;
		}

Initial URL


Initial Description
Usage:
 formatDecimals(3.1415926, 3);
returns: 3.141.
Also adds zeros to end if needed.

Initial Title
Format Decimals

Initial Tags
number, math

Initial Language
ActionScript 3