【JavaScript】常用的函数


秒 替换成 分钟:秒

var formatSeconds = function (value){
    var arr = [];
    if (parseInt((value / 60 / 60) + "")) {
        arr.push(parseInt((value / 60 / 60) + ""));
    }
    arr.push(parseInt((value / 60 % 60) + ""), parseInt((value % 60) + ""));
    return arr.join(":").replace(/\b(\d)\b/g, "0$1");
}

保留小数点后N位

  • 方法一
var getFloat = function (num, n){
    n = n ? parseInt(n) : 0;
    if (n <= 0) {
        return Math.round(num);
    }
    num = Math.round(num * Math.pow(10, n)) / Math.pow(10, n);
    return num;
}
  • 方法二
 num.toFixed(n)

num 必须是 number 类型。
toFixed() 的四舍五入是不稳定的,在不同的浏览器上得到的结果是不同的。

"alert(0.009.toFixed(2))" type="button" value="显示0.009.toFixed(2)">  

在ie7下点击按钮会显示0.00,而ff会是0.01。

"alert(0.097.toFixed(2))" type="button" value="显示0.097.toFixed(2)">  

ie和ff都正常。

解决方案:

Number.prototype.toFixed = function( fractionDigits )  
{  
    //没有对fractionDigits做任何处理,假设它是合法输入  
    return (parseInt(this * Math.pow( 10, fractionDigits  ) + 0.5)/Math.pow(10,fractionDigts)).toString();  
}  

你可能感兴趣的:(JavaScript)