NumberUtils.as 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package {
  2. public class NumberUtils {
  3. public static function formatNumber (i:Number) : String{
  4. var format:NumberFormat = NumberFormat.getInstance(null);
  5. return NumberUtils.format (i,
  6. format.numDecimals,
  7. format.isFixedNumDecimalsForced,
  8. format.isDecimalSeparatorComma,
  9. format.isThousandSeparatorDisabled
  10. );
  11. }
  12. public static function formatNumberY2 (i:Number) : String{
  13. var format:NumberFormat = NumberFormat.getInstanceY2(null);
  14. return NumberUtils.format (i,
  15. format.numDecimals,
  16. format.isFixedNumDecimalsForced,
  17. format.isDecimalSeparatorComma,
  18. format.isThousandSeparatorDisabled
  19. );
  20. }
  21. public static function format(
  22. i:Number,
  23. numDecimals:Number,
  24. isFixedNumDecimalsForced:Boolean,
  25. isDecimalSeparatorComma:Boolean,
  26. isThousandSeparatorDisabled:Boolean
  27. ) : String {
  28. if ( isNaN (numDecimals )) {
  29. numDecimals = 4;
  30. }
  31. // round the number down to the number of
  32. // decimals we want ( fixes the -1.11022302462516e-16 bug)
  33. i = Math.round(i*Math.pow(10,numDecimals))/Math.pow(10,numDecimals);
  34. var s:String = '';
  35. var num:Array;
  36. if( i<0 )
  37. num = String(-i).split('.');
  38. else
  39. num = String(i).split('.');
  40. //trace ("a: " + num[0] + ":" + num[1]);
  41. var x:String = num[0];
  42. var pos:Number=0;
  43. var c:Number=0;
  44. for(c=x.length-1;c>-1;c--)
  45. {
  46. if( pos%3==0 && s.length>0 )
  47. {
  48. s=','+s;
  49. pos=0;
  50. }
  51. pos++;
  52. s=x.substr(c,1)+s;
  53. }
  54. if( num[1] != undefined ) {
  55. if (isFixedNumDecimalsForced){
  56. num[1] += "0000000000000000";
  57. }
  58. s += '.'+ num[1].substr(0,numDecimals);
  59. } else {
  60. if (isFixedNumDecimalsForced && numDecimals>0){
  61. num[1] = "0000000000000000";
  62. s += '.'+ num[1].substr(0,numDecimals);
  63. }
  64. }
  65. if( i<0 )
  66. s = '-'+s;
  67. if (isThousandSeparatorDisabled){
  68. s=s.replace (",","");
  69. }
  70. if (isDecimalSeparatorComma) {
  71. s = toDecimalSeperatorComma(s);
  72. }
  73. return s;
  74. }
  75. public static function toDecimalSeperatorComma (value:String) : String{
  76. return value
  77. .replace(".","|")
  78. .replace(",",".")
  79. .replace("|",",")
  80. }
  81. }
  82. }