AS3 Convert Numbers to Words


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

Full credit for this goes to Deva Raj (@nsdevaraj). This is also a good function for doing a similar thing, http://snipplr.com/view/27954/as3-convert-a-number-to-a-string/


Copy this code and paste it in your HTML
  1. package
  2. {
  3. public class NumberUtil
  4. {
  5. //Usage: trace(NumberUtil.converToWords(numbers));
  6. private static const THOUSANDS:Array = ['','Thousand','Million','Billion','Trillion'];
  7. private static const DECADES:Array = ['Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety'];
  8. private static const TENS:Array = ['Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen'];
  9. private static const DIGITS:Array = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'];
  10. private static const HUNDRED:String = 'Hundred ';
  11. private static const POINT:String ='point ';
  12. private static const BIG:String ='Too big'
  13. public static function converToWords(num:Number):String {
  14. var s:String = num.toString();
  15. s = s.replace(/[\, ]/g,'');
  16. var x:int = s.indexOf('.');
  17. if (x == -1) x = s.length;
  18. if (x > 15) return BIG;
  19.  
  20. var number:Array = s.split('');
  21. var Words:String = '';
  22. var cnt:int = 0;
  23.  
  24. for (var i:int=0; i < x; i++) {
  25. if ((x-i)%3==2) {
  26. if (number[i] == '1') {
  27. Words += TENS[Number(number[i+1])] + ' ';
  28. i++;
  29. cnt=1;
  30. }
  31. else if (number[i]!=0){
  32. Words += DECADES[number[i]-2] + ' ';
  33. cnt=1;
  34. }
  35. }else if (number[i]!=0) {
  36. Words += DIGITS[number[i]] +' ';
  37. if ((x-i)%3==0) Words += HUNDRED;
  38. cnt=1;
  39. }
  40. if ((x-i)%3==1) {
  41. if (cnt) Words += THOUSANDS[(x-i-1)/3] + ' ';
  42. cnt=0;
  43. }
  44. }
  45. if (x != s.length) {
  46. var y:int = s.length;
  47. Words += POINT;
  48. for (var j:int=x+1; j<y; j++) Words += DIGITS[number[j]] +' ';
  49. }
  50. return Words.replace(/\s+/g,' ');
  51. }
  52. }
  53. }
  54.  
  55. // USAGE EXAMPLE
  56. // var myNumber:int = 2319854;
  57. // trace("myNumber: " + myNumber);
  58. // var myNumberWords:String = NumberUtil.converToWords(myNumber);
  59. // trace("myNumberWords: " + myNumberWords);
  60. //
  61. // OUTPUT
  62. // myNumber: 2319854
  63. // myNumberWords: Two Million Three Hundred Nineteen Thousand Eight Hundred Fifty Four

URL: http://nsdevaraj.wordpress.com/2010/11/17/convert-int-to-string/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.