Thursday, April 25, 2024
98
rated 0 times [  101] [ 3]  / answers: 1 / hits: 94335  / 16 Years ago, thu, february 19, 2009, 12:00:00

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:



0.5 1 0


1.5 2 2


2.5 3 2



In FF 3.03 I get:



0.5 1 1


1.5 2 2


2.5 3 3



In IE 7 I get:



0.5 1 0


1.5 2 2


2.5 3 3



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?


More From » cross-browser

 Answers
58

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.


[#99948] Thursday, February 12, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cartersinceren

Total Points: 442
Total Questions: 116
Total Answers: 106

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
cartersinceren questions
Thu, Nov 5, 20, 00:00, 4 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Fri, Feb 1, 19, 00:00, 5 Years ago
;