/ Published in: ActionScript 3
Usage: formatDecimals(3.1415926, 3); returns: 3.141. Also adds zeros to end if needed.
Expand |
Embed | Plain Text
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; }
Comments
Subscribe to comments
You need to login to post a comment.

This built-in method will do the same thing: num.toFixed(3);
@TandemAdam: toFixed() surely does its job but if you have some oldschool project made in AS2 and you don't want to re-code it into AS3, this snippet will save your 4ss ;-)