【问题标题】:Why do some rounded JavaScript values round the wrong way?为什么某些舍入的 JavaScript 值会以错误的方式舍入?
【发布时间】:2015-05-11 16:29:30
【问题描述】:

在谷歌搜索 1 个半小时后,我尝试了许多脚本,但都给了我错误的四舍五入数字或完全错误的值。这是我试过的两个脚本。

FIRST TRY:
    Number.prototype.round = function(p) {
      p = p || 10;
      return parseFloat( this.toFixed(p) );
    };


SECOND TRY:
    function roundNumber(number, decimals) { 
        var newnumber = new Number(number+'').toFixed(parseInt(decimals));
        return  parseFloat(newnumber);
    }

我从两者中得到的一些示例输出:

0.22  ->  0.21480000000000005 (bad) should be 21
0.43  -> 0.4284 (good) 43 is right

我做错了什么?任何帮助将不胜感激,因为这让我戳了太久。

【问题讨论】:

  • 第二个sn-p代码非常糟糕,尤其是在new Number(number+'')

标签: javascript math rounding


【解决方案1】:

为什么不使用这样的东西:

Math.round(yourNumber * 100) / 100;

这会将它四舍五入到小数点后两位,这里或多或少地回答了相同的问题 - Round to at most 2 decimal places (only if necessary)

这是一个小例子

function round(num){
    var result = Math.round(num * 100) / 100;
    return console.log(result);
}

round(0.4284);

Fiddle 在这里进行测试:https://jsfiddle.net/ToreanJoel/bLzz2mL8/

【讨论】:

  • 这并没有回答为什么代码没有像 OP 预期的那样四舍五入的问题。
  • 谢谢!老实说,我不确定出了什么问题,但是在使用你的之后它可以工作:/我会给你一个赞成票,但我不能没有更多的代表......但是当我生病时回来支持 :) 这有效!
  • 没问题的人,@Martin - 我理解你的意思,我很抱歉,我尝试创建错误并提出了一个似乎可行的解决方案,但我很快就会更新我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-12
  • 2023-01-28
  • 1970-01-01
  • 2022-11-14
  • 2013-03-19
  • 1970-01-01
  • 2010-10-31
相关资源
最近更新 更多