Posted By

Mijos on 01/22/09


Tagged

number math decimal round


Versions (?)

Format Decimals


 / Published in: ActionScript 3
 

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

  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
Posted By: TandemAdam on October 8, 2009

This built-in method will do the same thing: num.toFixed(3);

Posted By: MaRmAR on January 24, 2011

@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 ;-)

You need to login to post a comment.