Math.round()&中的舍入问题.toFixed() [英] Rounding issue in Math.round() & .toFixed()
本文介绍了Math.round()&中的舍入问题.toFixed()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在下面使用了两种方法:
I used below two methods :
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()
function&我得到了正确的答案。
Mathematically alert should be 239.53
but its giving 239.52
as output.
So i tried using .toFixed()
function & i got proper answer.
但当我试图获得 239.575
的答案时,它再次给出了错误的输出。
But when i try to get answer for 239.575
it gives again wrong output.
alert((239.575).toFixed(2));
此输出应为 239.58
而不是给予 239.57
。
Here output should be 239.58
instead its giving 239.57
.
此错误在最终输出中产生一点差异。那么有人可以帮我解决这个问题吗?
This error creating a bit difference in final output. So can anyone help me to sort this out?
推荐答案
这种方法会给出非常正确的圆形结果。
This method will give very correct round result.
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()&中的舍入问题.toFixed()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文