ActionScript 3 AS3将数字转换为单词

Posted

tags:

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

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

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

ActionScript 3 AS3将DisplayObject转换为黑白

ActionScript 3 AS3将百分比转换为值

ActionScript 3 AS3按名称将对象转换为类

ActionScript 3 AS3将整数转换为二进制值

ActionScript 3 将Java DateTime转换为AS3日期

ActionScript 3 AS3将字符串转换为函数名称