Javascript functions Math.round(num) vs num.toFixed(0) and browser inconsistencies

Posted by eft on Stack Overflow See other posts from Stack Overflow or by eft
Published on 2009-02-19T18:31:57Z Indexed on 2012/09/01 21:38 UTC
Read the original article Hit count: 280

Filed under:
|

Edit: To clarify, the problem is how to round a number to the nearest integer. i.e. 0.5 should round to 1 and 2.5 shoud round to 3.

Consider the following code:

<html><head></head><body style="font-family:courier">
<script>
for (var i=0;i<3;i++){
   var num = i + 0.50;
   var output = num + " " + Math.round(num) + " " + num.toFixed(0);
   var node = document.createTextNode(output);
   var pElement = document.createElement("p");
   pElement.appendChild(node);
   document.body.appendChild(pElement);
}
</script>
</body></html>

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. Does this mean that toFixed(0) should be avoided?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about cross-browser