To address your two original issues/questions:
Math.round(num) vs num.toFixed(0)
The issue here lies in the misconception that these should always give the same result. They are, in fact, governed by different rules. Look at negative numbers, for example. Because Math.round
uses "round half up" as the rule, you will see that Math.round(-1.5)
evaluates to -1
even though Math.round(1.5)
evaluates to 2
.
Number.prototype.toFixed
, on the other hand, uses what is basically equivalent to "round half away from zero" as the rule, according to step 6 of the spec, which essentially says to treat negatives as positive numbers, and then add back the negative sign at the end. Thus, (-1.5).toFixed(0) === "-2"
and (1.5).toFixed(0) === "2"
are true statements in all spec-compliant browsers. Note that these values are strings, not numbers. Note further that both -1.5.toFixed(0)
and -(1.5).toFixed(0)
are === -2
(the number) due to operator precedence.
Browser inconsistencies
Most modern browsers—or at least the ones you might be expected to support at the time of this writing except for IE—should all implement the specs correctly. (According to Renee's comment, the toFixed
issue you pointed out in Opera has been fixed, presumably since they started using the same JS engine as Chrome.) It's still worth reiterating that, even if the specs were implemented consistently across all browsers, the behavior defined in the spec, particularly for toFixed
rounding, can still be a bit unintuitive for "mere mortal" JS developers who expect true mathematical accuracy—see Javascript toFixed Not Rounding and this "works as intended" bug that was filed on the V8 JS engine for examples.
Conclusion
In short, these are two different functions with two different return types and two different sets of rules for rounding.
As others have suggested, I would also like to say "use whichever function fits your particular use case" (taking special care to note the peculiarities of toFixed
, especially IE's errant implementation). I would personally lean more towards recommending some explicit combination of Math.round/ceil/floor
, again, as others have mentioned. Edit: ...though, after going back and reading your clarification, your use case (rounding to a whole number) definitely calls for the aptly-named Math.round
function.