JavaScript round错误ToFixed,NumberPrototypeRound

时间:2017-01-29 18:35:09

标签: javascript rounding

我尝试了很多东西,但我仍有问题, 例如:4.3725 * 350 = 1530.38但我的结果是1530.37; /

我试过了:

Number.prototype.round = function(places) {
  return +(Math.round(this + "e+" + places)  + "e-" + places);
}

和toFixed。

1 个答案:

答案 0 :(得分:0)

你可以使用toPrecision()。这将返回一个字符串,您可以将其转换回数字和圆形 问题是toFixed()舍入这样的数字:3.65.toFixed(1)=> 3.6
Math.round():https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
这是一个例子:

   function roundTo(number, digits)  {
        var roundHelp = Math.pow(10, digits); // needed to round to correct number of decimals
        number = Number(number.toPrecision(15));
        return Math.round(number * roundHelp)/roundHelp;
        // if you want the exact number of digits use this return statement:
        // return (Math.round(number * roundHelp)/roundHelp).toFixed(digits);
   }
   var x = roundTo(4.3725 * 350, 2);  // x = 1530.38
   var y = roundTo(4.2970 * 535, 2);  // y = 2298.9