Javascript toFixed function

前端 未结 6 1745
春和景丽
春和景丽 2020-12-30 04:51

The expected result of:

(1.175).toFixed(2) = 1.18 and
(5.175).toFixed(2) = 5.18

But in JS showing:

6条回答
  •  一个人的身影
    2020-12-30 05:32

    It's because the numbers are stored as IEEE754.

    I would recommend you to use the Math class (round, floor or ceil methods, depending on your needing).

    I've just created a class MathHelper that can easily solve your problem:

    var MathHelper = (function () {
        this.round = function (number, numberOfDecimals) {
            var aux = Math.pow(10, numberOfDecimals);
            return Math.round(number * aux) / aux;
        };
        this.floor = function (number, numberOfDecimals) {
            var aux = Math.pow(10, numberOfDecimals);
            return Math.floor(number * aux) / aux;
        };
        this.ceil = function (number, numberOfDecimals) {
            var aux = Math.pow(10, numberOfDecimals);
            return Math.ceil(number * aux) / aux;
        };
    
        return {
            round: round,
            floor: floor,
            ceil: ceil
        }
    })();
    

    Usage:

    MathHelper.round(5.175, 2)
    

    Demo: http://jsfiddle.net/v2Dj7/

提交回复
热议问题