Format Decimals


/ Published in: ActionScript 3
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. function formatDecimals(num:Number, digits:uint):String
  2. {
  3. var tenToPower:Number = Math.pow(10, digits);
  4. var cropped:String = String(Math.round(num * tenToPower) / tenToPower);
  5.  
  6. var decimalPosition:int;
  7.  
  8. for (var i:int = 0; i < cropped.length; i++)
  9. {
  10. if (cropped.charAt(i) == ".")
  11. {
  12. decimalPosition = i;
  13. }
  14. }
  15.  
  16. var output:String = cropped;
  17. var decimals:String = cropped.substr(decimalPosition + 1, cropped.length);
  18. var missingZeros:Number = digits - decimals.length;
  19.  
  20. if (decimals.length < digits && decimalPosition > 0)
  21. {
  22. for (var j:int = 0; j < missingZeros; j++)
  23. {
  24. output += "0";
  25. }
  26. }
  27.  
  28. return output;
  29. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.