小菜AS3之路

2012.2.17
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

取整、取小数点位数

Posted on 2012-10-18 16:25  枫雨  阅读(808)  评论(0编辑  收藏  举报

as3中的取整、取小数点位数

Math.round()方法:

Math.round()可以四舍五入对数字取整

1
2
trace(Math.round(39.88));   //输出40
trace(Math.round(58.33));   //输出58

Math.floor()方法:

Math.floor()可以向下取整

1
2
trace(Math.floor(39.88));   //输出39
trace(Math.floor(58.33));   //输出58

Math.ceil()方法:

Math.ceil()可以向上取整

1
2
trace(Math.ceil(39.88));    //输出40
trace(Math.ceil(58.33));    //输出59

toFixed()方法:

toFixed()方法四舍五入取指定位数的小数点,当其中参数为0时表示不留小数点

1
2
3
4
5
var temp:Number=3.1415926
//toFixed()中的参数就是需要取的小数位数,0表示不留小数点
trace(temp.toFixed(0));     //输出3
temp=18.888;
trace(temp.toFixed(0));     //输出19

==============================

Math.round()方法取小数位数:

比如说3.14159要精确到.001位,则先3.14159/.001,然后再Math.round(3.14159/.001),最后在把结果乘以需要精确的位数Math.round(3.14159/.001)*.001

1
2
trace(Math.round(3.14159/.001)*.001);   //输出3.142
trace(Math.round(3.14159/.01)*.01); //输出3.14

如果不想四舍五入,那直接改round()方法为floor()或者ceil()方法即可

toFixed()方法取小数位数:

直接指定toFixed()中的参数即可,比如要留两位小数,则toFixed(2)

1
2
3
4
var temp:Number=3.1415926
trace(temp.toFixed(1));     //输出3.1
temp=18.888;
trace(temp.toFixed(2));     //输出18.89