当前位置: > > > Flex4 - 使用科学计数法表示数字

Flex4 - 使用科学计数法表示数字

在图表/表格或其他一些情况下,如果数字过大或者过小,直接显示的话会不便于阅读。这个时候就需要把数字转换成科学计数法再显示。比如:123456789可以显示成123.5M。

转换类:
package
{
	import spark.formatters.NumberFormatter;

	public class PrefixHelper
	{
		private static var _prefixesOfBigNumbers:Array = [
			{number:1000, prefix:"k"},
			{number:1000000, prefix:"M"}, 
			{number:1000000000, prefix:"G"},
			{number:1000000000000, prefix:"T"}, 
			{number:1E15, prefix:"P"},
			{number:1E18, prefix:"E"}, 
			{number:1E21, prefix:"Z"}, 
			{number:1E24, prefix:"Y"}];
		
		private static var _prefixesOfSmallNumbers:Array = [
			{number:1E-24, prefix:"y"}, 
			{number:1E-21, prefix:"z"}, 
			{number:1E-18, prefix:"a"}, 
			{number:1E-15, prefix:"f"}, 
			{number:1E-12, prefix:"p"}, 
			{number:1E-9, prefix:"n"}, 
			{number:1E-6, prefix:"μ"},
			{number:0.001, prefix:"m"}];
		
		
		public static function addPrefix(value:Number, 
										 prefixesOfBigNumbers:Array = null, 
										 prefixesOfSmallNumbers:Array = null, 
										 precision:Number = 1):String{
			
			if(prefixesOfBigNumbers == null){
				prefixesOfBigNumbers = _prefixesOfBigNumbers;
			}
			if(prefixesOfSmallNumbers == null){
				prefixesOfSmallNumbers = _prefixesOfSmallNumbers;
			}
				
			var numberFormat:NumberFormatter = new NumberFormatter();
			
			var c:Number;
			var newVal:Number;
			var prec:Number;
			var str:String = numberFormat.format(value);
			var sign:String = "";
			if (value == 0){
				return ("0");
			};
			if (value < 0){
				sign = "-";
			};
			value = Math.abs(value);
			if (value > 1){
				c = (prefixesOfBigNumbers.length - 1);
				while (c > -1) {
					if (value >= prefixesOfBigNumbers[c].number){
						newVal = (value / prefixesOfBigNumbers[c].number);
						//prec = Number(numberFormat.precision);
						prec = precision;
						if (prec < 1){
							prec = 1;
						};
						
						newVal = roundTo(newVal, prec);
						str = ((((sign + "") + newVal) + "") + prefixesOfBigNumbers[c].prefix);
						break;
					};
					c--;
				};
			} else {
				c = 0;
				while (c < prefixesOfSmallNumbers.length) {
					if (value <= prefixesOfSmallNumbers[c].number){
						newVal = (value / prefixesOfSmallNumbers[c].number);
						prec = Math.abs(Math.round((Math.log(newVal) * Math.LOG10E)));
						newVal = roundTo(newVal, prec);
						str = ((((sign + "") + newVal) + "") + prefixesOfSmallNumbers[c].prefix);
						break;
					};
					c++;
				};
			};
			return (str);
		}
		
		public static function roundTo(num:Number, precision:Number):Number{
			precision = Math.round(precision);
			var p:Number = Math.pow(10, precision);
			return ((Math.round((num * p)) / p));
		} 
	}
}
使用:
ll.text = addPrefix(123456789);   //123.5M
ll.text = addPrefix(0.0000123456); //0.01m
评论0