Format Number in ActionScript


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

This code was adapted from a snippet I found somewhere awhile back... can't claim complete credit


Copy this code and paste it in your HTML
  1. function numberFormat(number, decimals, thousands_sep, decimal_sep) {
  2. // var_number.number_format([decimals ,thousand separator,decimal separator]);
  3. // var number: number to format
  4. // decimals: how many decimal numbers (default value 0);
  5. // thousand separator: char that define the thousandecimal_sep (default value ,);
  6. // decimal separator: char the defines the decimals (default value .);
  7.  
  8. if(isNaN(number)) return undefined;
  9. if(decimals < 0) return undefined;
  10. if(decimals == undefined) decimals = 0;
  11. if(thousands_sep == undefined) thousands_sep = ',';
  12. if(decimal_sep == undefined) decimal_sep = '.';
  13.  
  14. var returned = number.toString().split('.'), str_begin, str_after, temp_str = "", i;
  15.  
  16. if(returned.length == 1) {
  17. str_begin = returned[0]
  18. str_after = '';
  19. } else if(returned.length == 2) {
  20. str_begin = returned[0];
  21. str_after = returned[1];
  22. str_after = str_after.substr(0, 2);
  23. } else {
  24. trace("uncaught number format");
  25. }
  26.  
  27. // thousands seperator
  28. if(str_begin.length > 3) {
  29. for(i = 0; i < str_begin.length; i++) {
  30. if(((str_begin.length - i) % 3) == 0 && i != str_begin.length - 1) {
  31. temp_str = temp_str + thousands_sep + str_begin.charAt(i);
  32. } else {
  33. temp_str = temp_str + str_begin.charAt(i);
  34. }
  35. }
  36. } else {
  37. temp_str = str_begin;
  38. }
  39.  
  40. // ----------------------
  41. // decimals
  42. // if decimals==0 return
  43. // ----------------------
  44. if(decimals > 0) {
  45. str_after = str_after.substr(0, decimals);
  46.  
  47. if(str_after.length < decimals) {
  48. while(str_after.length < decimals) {
  49. str_after += '0';
  50. }
  51. }
  52. }
  53.  
  54. if(decimals > 0) {
  55. return temp_str + decimal_sep + str_after;
  56. } else {
  57. return temp_str;
  58. }
  59. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.