【JavaScript】数学计算的函数与数字的格式化

JavaScript中使用5中数学计算符号,+,-,*,/,%

  • 常用的函数

Math.ceil 向上取整,Math.ceil(4.2)的返回值为5

Math.floor  向下取整,Math.floor(4.7)的返回值为4

Math.round  四舍五入,Math.round(4.2)的返回值为4,Math.round(4.7)的返回值为5

Math.pow  计算幂值,Math.pow(2,4)返回16

Math.sqrt 开方计算,Math,sqrt(9)返回3

Math.random 生成随机数,返回一个0到1之间的(伪)随机数

  • 数学常量

Math.E  自然对数中的e

Math.PI  计算圆的面积时候用的(派)

  • 将数字转化为有x位小数位的形式
function roundTo(base,precision) {
    var m = Math.pow(10,precision);
    var a = Math.round(base*m)/m;
    return a;
}

例如:roundTo(3.942487,3) 返回3.942

  • 有范围的随机数
function randomBetween(min,max){
    return min+Math.floor(Math.random()*(max-min+1));
}

返回一个min到max之间的数

  • 将数字转换为字符串

var a=1;

a = String(a);或者a=a.toString(); 

也可以var a=10+''; 但是可读性较差

注意:var s = a+b+'m';得到的结果是数字(a+b)然后拼接字符串

  • 字符串转化为数字

a=Number(a);

var a = '24.68mmmmm';  当字符串不以数字开头时不能转化 如'mmm26.7'

a = parseInt(a,10);

a=parseFloat(a);

猜你喜欢

转载自www.cnblogs.com/to-red/p/10066771.html