在js中Math函数函数可以包括各种方法,如有:Math.random():Math.round();Math.floor(); 和Math.ceil();相反,Math.floor();等下面我来介绍一下。
Math函数主要用于数字的处理
Math.random():可以产生出0-1之间的任意小数,例如0.0105901374530933 或 0.872525005541986
Math.round();是采用四舍五入方式取得最接近的整数
Math.ceil();是向上取得一个最接近的整数
Math.floor(); 和Math.ceil();相反,Math.floor();向下取得一个最接近的整数。
Math.round(Math.random());
这个表达式可以生成一个0.0和1.0之间的一个数,然后四舍五入取得一个整数。这样所生成的数字就是0或1。这个表达式可以用在各有50%的可能的情况下
Math.sqrt():平方根,如果是非数值类型的,返回一个NaN
Math.pow(a,b):a是底数,b是指数
例
代码如下 |
|
var a=6.448;
var b=9;
document.write("进一取整:"+Math.ceil(a)+"<br />");
document.write("去尾取整:"+Math.floor(a)+"<br />");
document.write("四舍五入取整:"+Math.round(a)+"<br />");
document.write("返回最小值:"+Math.min(a,b)+"<br />");
document.write("返回最大值:"+Math.max(a,b)+"<br />");
document.write("求幂,a的b次方:"+Math.pow(a,b)+"<br />");
document.write("生成0-1之间的随机数:"+Math.random()+"<br />");
document.write("开平方:"+Math.sqrt(b)+"<br />");
|