Monday, May 20, 2024
171
rated 0 times [  173] [ 2]  / answers: 1 / hits: 194042  / 14 Years ago, sun, february 6, 2011, 12:00:00

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.


More From » floating-point

 Answers
27

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);
}

[#93872] Friday, February 4, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shane

Total Points: 239
Total Questions: 91
Total Answers: 114

Location: Faroe Islands
Member since Tue, Jul 7, 2020
4 Years ago
;