4.4.格式化输出

问题
我要把数字进行格式化输出
解决办法
用NumberFormat 类,设置掩码,然后调用format( ) 方法。
讨论
经常会遇到需要在输出时在头部和尾部加0或空格来达到格式化输出的目的,比如显示时间或日期。比如要格式化输出6小时3分钟,显示为6:03 或06:03,而不是6:3。而且还经常碰到输出时进行对齐等,这都需要进行格式化输出:
123456789
1234567
12345
虽然自己都可以做到这种效果,但是你会发现用NumberFormat 对象更简单更灵活。
NumberFormat 类是个自定义类,可到http://www.rightactionscript.com/ascb下载。使用它须先导入:import ascb.util.NumberFormat:
接下来决定是什么掩码进行格式化,它可以是0,#,.,,,或者其他。
零(0)
使用零作为占位符
井号(#)
点号(.)
逗号(,)
下面看一下例子:掩码如下:
##,###.0000
格式化如下数字:1.2345, 12.345, 123.45, 1234.5, 和12345, 结果:
1.2345
12.3450
123.4500
1,234.5000
12,345.0000
通过构造函数直接传入参数作为掩码:
+展开
-ActionScript
var styler:NumberFormat = new NumberFormat("##,###.0000");
另外,使用属性进行修改掩码:
+展开
-ActionScript
styler.mask = "##.00";

设置好掩码,调用format( ) 方法就可以格式化数字了:
+展开
-ActionScript
trace(styler.format(12345);
var styler:NumberFormat = new NumberFormat("#,###,###,###");
trace(styler.format(1));
trace(styler.format(12));
trace(styler.format(123));
trace(styler.format(1234));
styler.mask = "#,###,###,###.0000";
trace(styler.format(12345));
trace(styler.format(123456));
trace(styler.format(1234567));
trace(styler.format(12345678));
trace(styler.format(123456789));

输出如下:
1
12
123
1,234
12,345.0000
123,456.0000
1,234,567.0000
12,345,678.0000

123,456,789.0000
NumberFormat 对象自动本地化返回值。如果Flash 播放器在英文操作系统上运行,NumberFormat 类是用逗号和点号,如果在法语操作系统上运行,正好相反,使用点号和逗号,因此需要覆盖自动本地化:

有几种方法覆盖自动本地化设置:
把Locale 对象作为format( ) 方法的第二个参数,format( ) 方法根据Locale 对象的设置进行格式化。Locale 对象使用两个参数,第一个是语言代码,如en,第二个参数为国家代码,如

EN.

通过全局设置Locale.slanguage 或Locale.svariant 属性就不需要给format( ) 方法传递参数了使用符号对象作为format( )的第二个参数,包括两个属性:group和decimal。该方法适合没有用Locale对象进行全局设置下使用。

Locale 类在ascb.util 包中,使用前导入。
下面的代码展示了三种方法:
+展开
-ActionScript
var styler:NumberFormat = new NumberFormat("#,###,###,###.00");
Locale.slanguage = "fr";
trace(styler.format(1234));
trace(styler.format(12345, {group: ",", decimal: "."}));
trace(styler.format(123456));
Locale.slanguage = "en";
trace(styler.format(1234567));
trace(styler.format(12345678, new Locale("es""ES")));
trace(styler.format(123456789, {group: "|", decimal: ","}));

结果:
1.234,00
12,345.00
123.456,00
1,234,567.00
12.345.678,00
123|456|789,00

加支付宝好友偷能量挖...


评论(0)网络
阅读(87)喜欢(0)flash/flex/fcs/AIR