AS3将数字转换为单词

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AS3将数字转换为单词相关的知识,希望对你有一定的参考价值。

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/
  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

以上是关于AS3将数字转换为单词的主要内容,如果未能解决你的问题,请参考以下文章

ActionScript 3 AS3将数字转换为字符串

AS3将数字转换为字符串

编写代码将给定的数字转换为单词(例如 1234 作为输入应该输出 1234)

在 PDF 表单中使用 JavaScript 将数字转换为单词

将 AS2 代码转换为 AS3 格式

将 as3 btn 代码转换为 Javascript