js四舍五入

/*

 * 四舍五入的相关问题

 */

 

    /* numObj.toFixed([fractionDigits])

     * toFixed 方法返回一个以定点表示法表示的数字的字符串形式。

     * 该字符串中小数点之前有一位有效数字,而且其后必须包含 fractionDigits 数字。

     * 缺点:保留小数点后fractionDigits位时,fractionDigits之前必须至少有一位>0

     */

 function do4out5in1(){

   

   

    var num = new Number("0.105").toFixed(2);//0.11

    alert("0.109 == " + num);//0.11

   

    var num = new Number("-1.109").toFixed(2);//-1.11

    alert("-1.109 == " + num);//-1.1

   

    var num = new Number("-0.14").toFixed(1);//-0.2

    alert("-0.14 == " + num);//0

   

    var num = new Number("0.009").toFixed(2);//0.01

    alert("0.009 == " + num);//0.00

 

    //toFixed()转换后为String类型

    var num = new Number("9.009").toFixed(2);//9.009

    alert(num + 1);//9.011

    alert(typeof(num));//string

    alert(new Number(num) + 1);//10.01

   

 }

   

 /*

  * 解决toFixed四舍五入问题,替换Number.prototype.toFixed 如下

  * Math.pow(底数,几次方)

  * 缺点:但只适用于正数,负数的结果错

  */

 Number.prototype.toFixed = function(s)

{

    return (parseInt(this * Math.pow( 10, s ) + 0.5)/ Math.pow( 10, s )).toString();

}

 

 

 /*

  * Math.round()四舍五入,1.52-1.5-1.5

  * 缺点:结果只为整数(即有效位为:小数点后一位),没有小数位,不支持保留小数点有效位

  */

 function do4out5in2(){

 

    alert("1.5 == " + Math.round(1.5));//2

    alert("1.09 == " + Math.round(1.09));//1

    alert("-1.5 == " + Math.round(-1.5));//-1.5

    alert("-1.8 == " + Math.round(-1.8));//-2

 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值