·您当前的位置:首页 > 技术教程 > AS2与AS3技术 >

[AS3]as3进行取整计算、取小数点位数计算函数Math.round实例

时间:2015-01-04 17:19酷播
[AS3]as3进行取整计算、取小数点位数计算函数,Math.floor,Math.round

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

热门文章推荐

请稍候...

保利威视云平台-轻松实现点播直播视频应用

酷播云数据统计分析跨平台播放器