zoukankan      html  css  js  c++  java
  • js 保留2位小数 四舍五入Math.toFixed() bug

    1 toFixed方法

    toFixed方法可以把Number四舍五入位指定小数位数的数字。但是其四舍五入的规则与数学中的规则不同,使用的是银行家舍入规则。

    银行家舍入:

    四舍六入五取偶(四舍六如五留双),简单就是说:四舍六入五考虑,五后非0进1,五后为0看奇偶,五前为偶应舍去,五前为奇要进1.

    > (3.61).toFixed(1)    //四舍
    '3.6'
    > (3.69).toFixed(1)    //六入
    '3.7'
    > (3.651).toFixed(1)    //五考虑,五后非零,进
    '3.7'
    > (3.65).toFixed(1)    //五考虑,五后为零,五前为偶数,舍去
    '3.6'
    > (3.75).toFixed(1)    //五考虑,五后为零,五前为奇数,进
    '3.8'

    显然这种规则不符合我们平常在数据中处理的方式。我们可以使用Math.round()方法进行自定义式的实现

    round()方法可把一个数字舍入为最接近的整数。跟数学中的取舍的规则一样。对于0.5该方法进行上舍入;

    实例
    把不同的数舍入为最接近的整数:

    Math.round(0.60)//1
    Math.round(0.50) //1
    Math.round(0.49)//0
    Math.round(-4.40) //-4
    Math.round(-4.60)//-5

    可以利用round方法对数字进行四舍五入的处理:

    Number.prototype.toFixed = function(d) {
    var  changeNum=this+'';//把数字转为字符串
    if(changeNum.indexOf('-')!=-1)//判断是否是负数
    changeNum=Math.abs(changeNum);
          changeNum = (Math.round(changeNum * Math.pow(10, d)) / Math.pow(10, d)).toString();
        
        var index = changeNum.indexOf('.');//判断字符是否有小数点
        if (index == -1) {//如果没有小数点,加上对应个数的小数点
            changeNum += '.';
            changeNum += new Array(d+1).join('0');
        } else if (index > 0) {//如果有,index是小数点的坐标值,比如在第二位index=1
            var temp = d - (changeNum.length - index - 1);//小数点后的位数小于要取舍的个数,用0补齐;数字的长度-小数点的坐标值-1=小数的位数(小数点也占以为,4.00 length:4;.的index是1)
            if (temp > 0) {
                changeNum += new Array(temp+1).join('0');
            }
    
        }
          if (this.toString().indexOf('-') != -1) {//如果是负数,加上-
            changeNum = "-" + changeNum;
        }
        return changeNum;
    }
    
    解析:
    
    this*Math.pow(10,s)//把要处理的数字乘以100*要取舍的位数,变成整数,舒勇Math.round()进行取舍,再除于100*要取舍的位数;
    比如对数字保留2位数:
    
    Math.round(3.555*100)/100//3.56

    参考:https://blog.csdn.net/Archimelan/article/details/83017518

  • 相关阅读:
    构造函数
    Php基础知识测试题答案与解释
    bootstrap简介
    ajax删除数据(不跳转页面)
    ajax基础部分
    Jquery弹出窗口
    JSON
    Jquery之JSON的用法
    Jquery基本用法
    php购物车(练习)
  • 原文地址:https://www.cnblogs.com/xiaofenguo/p/13180660.html
Copyright © 2011-2022 走看看