在javascript中截断(不舍入)十进制数字 [英] Truncate (not round off) decimal numbers in javascript

查看:159
本文介绍了在javascript中截断(不舍入)十进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将十进制数字截断为小数位。就像这样:

  5.467  - > 5.46 
985.943 - > 985.94

toFixed(2)正确的事情,但它取决于价值。我不需要四舍五入的价值。希望这可以在JavaScript中。

解决方案

upd

因此,事实证明,无论你多么努力地补偿他们,四舍五入的错误总会困扰着你。因此,应该通过用十进制表示法来表示数字来攻击问题。

  Number.prototype.toFixedDown = function(digits){
var re = new RegExp((\\ d + \\\\\\\\\\\\\\\\\)的ToString()匹配(重新)。
返回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];
$ b $ // [5.46,985.94,17.56,0,23.1]

基于他人编译的老错误​​解决方案:

pre $ Number $原型.toFixedDown =函数(数字){
var n = this - Math.pow(10,-digits)/ 2;
n + = n / Math.pow(2,53); //添加1360765523:17.56.toFixedDown(2)===17.56
return n.toFixed(digits);
}


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.

解决方案

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中截断(不舍入)十进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆