在javascript中截断(不四舍五入)十进制数字

编程入门 行业动态 更新时间:2024-10-18 22:24:57
本文介绍了在javascript中截断(不四舍五入)十进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将十进制数字截断为小数位.像这样的:

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

5.467 -> 5.46 985.943 -> 985.94

toFixed(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中截断(不四舍五入)十进制数字

本文发布于:2023-11-10 02:40:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574112.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:四舍五入   十进制数   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!