javascriptfloating-pointfloating-accuracy

Truncate (not round off) decimal numbers in javascript


I am trying to truncate decimal numbers to decimal places. Something like this:

5.467   -> 5.46  
985.943 -> 985.94

toFixed(2) does just about the right thing but it rounds off the value. I don't need the value rounded off. Hope this is possible in javascript.


Solution

  • upd:

    So, after all it turned out, rounding bugs will always haunt you, no matter how hard you try to compensate them. Hence the problem should be attacked by representing numbers exactly in decimal notation.

    Number.prototype.toFixedDown = function(digits) {
        var re = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)"),
            m = this.toString().match(re);
        return m ? parseFloat(m[1]) : this.valueOf();
    };
    
    [   5.467.toFixedDown(2),
        985.943.toFixedDown(2),
        17.56.toFixedDown(2),
        (0).toFixedDown(1),
        1.11.toFixedDown(1) + 22];
    
    // [5.46, 985.94, 17.56, 0, 23.1]
    

    Old error-prone solution based on compilation of others':

    Number.prototype.toFixedDown = function(digits) {
      var n = this - Math.pow(10, -digits)/2;
      n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
      return n.toFixed(digits);
    }