/ Published in: ActionScript 3
Usage:
formatDecimals(3.1415926, 3);
returns: 3.141.
Also adds zeros to end if needed.
formatDecimals(3.1415926, 3);
returns: 3.141.
Also adds zeros to end if needed.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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; }