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/
package { public class NumberUtil { //Usage: trace(NumberUtil.converToWords(numbers)); private static const THOUSANDS:Array = ['','Thousand','Million','Billion','Trillion']; private static const DECADES:Array = ['Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety']; private static const TENS:Array = ['Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen']; private static const DIGITS:Array = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']; private static const HUNDRED:String = 'Hundred '; private static const POINT:String ='point '; private static const BIG:String ='Too big' public static function converToWords(num:Number):String { var s:String = num.toString(); s = s.replace(/[, ]/g,''); var x:int = s.indexOf('.'); if (x == -1) x = s.length; if (x > 15) return BIG; var number:Array = s.split(''); var Words:String = ''; var cnt:int = 0; for (var i:int=0; i < x; i++) { if ((x-i)%3==2) { if (number[i] == '1') { Words += TENS[Number(number[i+1])] + ' '; i++; cnt=1; } else if (number[i]!=0){ Words += DECADES[number[i]-2] + ' '; cnt=1; } }else if (number[i]!=0) { Words += DIGITS[number[i]] +' '; if ((x-i)%3==0) Words += HUNDRED; cnt=1; } if ((x-i)%3==1) { if (cnt) Words += THOUSANDS[(x-i-1)/3] + ' '; cnt=0; } } if (x != s.length) { var y:int = s.length; Words += POINT; for (var j:int=x+1; j<y; j++) Words += DIGITS[number[j]] +' '; } return Words.replace(/s+/g,' '); } } } // USAGE EXAMPLE // var myNumber:int = 2319854; // trace("myNumber: " + myNumber); // var myNumberWords:String = NumberUtil.converToWords(myNumber); // trace("myNumberWords: " + myNumberWords); // // OUTPUT // myNumber: 2319854 // myNumberWords: Two Million Three Hundred Nineteen Thousand Eight Hundred Fifty Four
以上是关于AS3将数字转换为单词的主要内容,如果未能解决你的问题,请参考以下文章
编写代码将给定的数字转换为单词(例如 1234 作为输入应该输出 1234)