Home  >  Q&A  >  body text

javascript - 金额,保留两位小数,四舍五入

问题:数字要保留两位小数,但是重写toFixed,大部分数据已经可以四舍五入,但是1.005类似的数据,四舍五入之后得到的数据是1.00,其实应该是1.01,求大神指点;

Number.prototype.toFixed = function (num) {

var changenum = (Number(this * Math.pow(10, num) + 0.5) / Math.pow(10, num)).toString();
index = changenum.indexOf(".");
if (index < 0 && num > 0) {
    changenum = changenum + ".";
    for (i = 0; i < num; i++) {
        changenum = changenum + "0";
    }
} else {
    index = changenum.length - index;
    for (i = 0; i < (num - index) + 1; i++) {
        changenum = changenum + "0";
    }
}
return changenum;

};

PHP中文网PHP中文网2772 days ago478

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-11 09:11:21

    1.005*100=100.5,Math.round四舍五入,得101再除100得1.01,能不能这样

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-11 09:11:21

    写的不大细

    <script>
        function change(num) {
                    if(typeof num != 'number') {
                        return
                    }
                    var numStr = num.toString();
                    var index = numStr.indexOf('.')
                    if(index == -1) {
                        return numStr += '.00'
                    } else if(numStr.length - index == 2) {
                        return numStr += '0'
                    } else if(numStr.length - index == 3) {
                        return numStr
                    } else {
                        var reg = /.(\d{3})\d*$/;
                        newNum = numStr.replace(reg, function($0, $1) {
                            //tempDec 用来判断四舍五入后小数位数
                            var tempDec = Math.round(Number($1.substring(0, 2) + '.' + $1.substring(2)));
                            var newDec;
                            tempDec = tempDec.toString();
                            tempDec == 0 ? newDec = '00' : (tempDec.length == 1 ? newDec = '0' + tempDec : newDec = tempDec)
                            return '.' + newDec
                        })
                    }
                    return newNum
                }
        </script>

    将var reg = /.(d{3})d+$/;改为了var reg = /.(d{3})d*$/;
    num != Number改为num != 'number'

    reply
    0
  • 迷茫

    迷茫2017-04-11 09:11:21

    function change(money){
        if(typeof money != 'number')return -1;
        return (100*money).toFixed(0)/100;
    }
    console.log(change(3.005));

    reply
    0
  • Cancelreply