我使用以下两种方法:
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
。此错误会在最终输出中产生一些差异。有人可以帮我解决这个问题吗?
最佳答案
此方法将给出非常正确的舍入结果。
function RoundNum(num, length) {
var number = Math.round(num * Math.pow(10, length)) / Math.pow(10, length);
return number;
}
只需调用此方法即可。
alert(RoundNum(192.168,2));