问题描述
请考虑以下代码:
for(var i = 0; i var num = i + 0.50;
var output = num ++ Math.round(num)++ num.toFixed(0);
alert(output);
}
在Opera 9.63中,我得到:
在FF 3.03中,我得到:
在IE 7中, p>
。为什么会出现这种不一致?这是否意味着应该避免 toFixed(0)
?
编辑:要回答您的编辑,请使用 Math.round
。
如果你喜欢这个语法,你也可以对Number
Number.prototype.round = function(){
return Math.round(this);
}
var num = 3.5;
alert(num.round())
我从未使用过 Number.toFixed()
之前(主要是因为大多数JS库提供了方法),但是根据你的结果,我会说使用 / code>方法(
round
, floor
, ceil
)then toFixed
如果跨浏览器一致性是你正在寻找。
Consider the following code:
for (var i=0;i<3;i++){
var num = i + 0.50;
var output = num + " " + Math.round(num) + " " + num.toFixed(0);
alert(output);
}
In Opera 9.63 I get:
In FF 3.03 I get:
In IE 7 I get:
Note the bolded results. Why are this inconsistencies present? Does this mean that toFixed(0)
should be avoided? What's the correct way to round a number to the nearest integer?
Edit: To answer your edit, use Math.round
. You could also prototype the Number
object to have it do your bidding if you prefer that syntax.
Number.prototype.round = function() {
return Math.round(this);
}
var num = 3.5;
alert(num.round())
I've never used Number.toFixed()
before (mostly because most JS libraries provide a toInt()
method), but judging by your results I would say it would be more consistent to use the Math
methods (round
, floor
, ceil
) then toFixed
if cross-browser consistency is what you are looking for.
这篇关于Math.round(num)vs num.toFixed(0)和浏览器不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!