打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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

 }

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
js取小数点后两位(四舍五入、直接截取)
javascript实现保留两位小数的多种方法
js小数运算出现多位小数如何解决
JavaScript 浮点数陷阱及解法
一篇文章带你了解JavaScript 数值方法(上篇)
Javascript四舍五入(Math.round()与Math.pow())
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服