【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() 的四舍五入是不稳定的,在不同的浏览器上得到的结果是不同的。

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

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

<input onclick="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();  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值