http://hi.baidu.com/cjmxp/blog/item/1a39d654fd2c765ed10906e7.html

用Math.round()可以4舍5入对数字取整。Math.floor()和Math.ceil()是对一个数向上或向下取整。自定义用NumberUtilities.round()的方法将一个数取整或取倍数。

    有许多的原因对数字取整。例如,当展示一个计算的结果时,可能只能展示这样的精确度。因为在ActionScript中所有的算术都是用浮点数执行,一些 未预料到的浮点数字的计算结果必须取整。例如,实际上以个计算的结果可能是3.999999,而理论上应该是4.0。
    Math.round()返回一个最接近参数的一个整数:
trace(Math.round(204.499)); // Displays: 204
trace(Math.round(401.5));    // Displays: 402
    Math.floor()向下取整,而Math.ceil()向上取整:
trace(Math.floor(204.99));   // Displays: 204
trace(Math.ceil(401.01));    // Displays: 402
    针对取整的小数的位置:
    1.确定想要近似的小数点的位置。例如,如果想要保留两位小数,把90.337近似为90.34,那就是说需要精确的0.01。
    2.将数字除以第一步中的精确值(这时候就是0.01)。
    3.用Math.round()对第2步的计算结果取整。
    4.用第2步的那个数乘于第3步的计算结果。
    例如,对90.337保留两位小数,可以这样:
trace (Math.round(90.337 / .01) * .01);   // Displays: 9.34
    可以用相同的方法对一个数近似取整到另一个整数。
    例如,对92.5近似取整到5:
trace (Math.round(92.5 / 5) * 5);   // Displays: 95
    对92.5近似取整到10:
trace (Math.round(92.5 / 10) * 10);   // Displays: 90
    在实际上,可以自定义一个NumberUtilites.round()方法实现这一功能。这个自定义方法有两个参数:
number
    需要近似取整的数字
roundToInterval
    近似取整的间隔。例如,如果要想近似到十分之一,用0.1作为间隔。要近似到6,用6做间隔。
    这个NumberUtilities类在ascb.util包中,因此想要是使用这个类首先要在文件中import来引入声明。看看一些例子:
trace(NumberUtilities.round(Math.PI));          // Displays: 3
trace(NumberUtilities.round(Math.PI, .01));     // Displays: 3.14
trace(NumberUtilities.round(Math.PI, .0001));   // Displays: 3.1416
trace(NumberUtilities.round(123.456, 1));       // Displays: 123
trace(NumberUtilities.round(123.456, 6));       // Displays: 126
trace(NumberUtilities.round(123.456, .01));     // Displays: 123.46
posted on 2009-03-10 09:38  sungo  阅读(479)  评论(0编辑  收藏  举报