本文介绍了在javascript中截断(不四舍五入)十进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将十进制数字截断为小数位.像这样的:
I am trying to truncate decimal numbers to decimal places. Something like this:
5.467 -> 5.46 985.943 -> 985.94toFixed(2) 做了几乎正确的事情,但它使值四舍五入.我不需要四舍五入的值.希望这在 javascript 中是可能的.
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.
推荐答案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); }更多推荐
在javascript中截断(不四舍五入)十进制数字
发布评论