Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Math.round()中的舍入问题。toFixed()_Javascript_Jquery - Fatal编程技术网

Javascript Math.round()中的舍入问题。toFixed()

Javascript Math.round()中的舍入问题。toFixed(),javascript,jquery,Javascript,Jquery,我使用了以下两种方法: Number.prototype.myRound = function (decimalPlaces) { var multiplier = Math.pow(10, decimalPlaces); return (Math.round(this * multiplier) / multiplier); }; alert((239.525).myRound(2)); 数学上的警报应该是239.53,但它的输出是239.52。 所以我尝试使用.toFix

我使用了以下两种方法:

Number.prototype.myRound = function (decimalPlaces) {
    var multiplier = Math.pow(10, decimalPlaces);

    return (Math.round(this * multiplier) / multiplier);
};
alert((239.525).myRound(2));
数学上的警报应该是
239.53
,但它的输出是
239.52
。 所以我尝试使用
.toFixed()
函数&我得到了正确的答案

但当我试图得到
239.575
的答案时,它又给出了错误的输出

alert((239.575).toFixed(2));
这里的输出应该是
239.58
,而不是它的给定值
239.57

此错误会在最终输出中产生位差异。有人能帮我解决这个问题吗?

round()
就可以了。试试这个:

var v= Math.round(239.575 * 100) / 100;
alert(v);

问题可能是浮点不准确,因此在不同的情况下(不同的数字集合、不同的浏览器等)可能会得到不同的结果


另请参见:在内部,239.575无法准确表示。在二进制中,0.575类似于1/2+1/16+1/128+1/256+

碰巧,用二进制表示,结果略小于239.575。因此,
Math.round
向下取整

要演示,请尝试以下方法:

alert(239.575 - 239.5)

您可能期望结果为0.075,但实际结果为0.0749999998863。

此方法将给出非常正确的四舍五入结果

function RoundNum(num, length) { 
    var number = Math.round(num * Math.pow(10, length)) / Math.pow(10, length);
    return number;
}
只要调用这个方法

alert(RoundNum(192.168,2));

只需使用
Math.round

function round(figureToRound){
    var roundOff = Math.round((figureToRound* 100 ).toFixed(2))/100;
    return roundOff;
}

console.log(round(1.005));

这将有助于圆满解决问题。

在我的软件中,我使用以下方法:

(要求)


有趣但
239.375.toFixed(2)
在Chrome31(Mac)中返回
“239.38”
。)@VisioN的可能副本不在此处。您使用的是哪种浏览器?我在Ubuntu上使用最新的FF。@CedricReichenbach Chrome 31在MacOSSimpler上的解决方案:虽然这是真的,但我在其他语言中从未见过这样的“问题”。。。这绝对是JavaScript中必须改进的地方。@这适用于任何使用双精度浮点数的语言。除了那些定点或任意精度的系统外,几乎所有的系统都是这样。它工作正常。它适用于所有条件。非常感谢。正如TJ Crowder在中提到的,请尝试RoundNum(35.855,2)。一个更好的答案可能是RoundNum(1.005,2)中的小数舍入示例被舍入为1,但预期1.01适用于所有情况。圆(239.575-239.5)0.08圆(239.575)239.58圆(239.525)239.53圆(1.005)1.01不适用于圆(0.07499)。它返回0.08,而不是0.07
Number.prototype.toFixed = function(fixed) {
    return (new Decimal(Number(this))).toFixed(parseFloat(fixed) || 
0);
};


var x = 1.005;
console.log( x.toFixed(2) ); //1.01
function bestRound(val, decimals){
    decimals = decimals || 2;
    var multiplier = Math.pow(10, decimals)
    return Math.round((val * multiplier ).toFixed(decimals)) / multiplier;
  }

bestRound(239.575 - 239.5)   0.08
bestRound(239.575)         239.58
bestRound(239.525)         239.53
bestRound(1.005)             1.01