www.webdeveloper.com
Results 1 to 2 of 2

Thread: toFixed not working consistently

  1. #1
    Join Date
    Jun 2010
    Posts
    1

    toFixed not working consistently

    Hi Guys,

    im new to this forum so i appologize if this thread is not properly placed.

    my problem is that im having a problem the toFixed function. it is not rounding numbers consistently. pasted below is a sample code where i have done some number testing:

    <html>
    <body>
    <script type="text/javascript">
    var num = new Number(1023.465);
    document.write(num.toFixed()+"<br />");
    document.write(num.toFixed(1)+"<br />");
    document.write(num.toFixed(2)+"<br />");
    document.write(num.toFixed(3)+"<br />");
    document.write('<br><br>');

    var num = new Number(1024.465);
    document.write(num.toFixed()+"<br />");
    document.write(num.toFixed(1)+"<br />");
    document.write(num.toFixed(2)+"<br />");
    document.write(num.toFixed(3)+"<br />");
    </script>
    </body>
    </html>

    the out from this code is as follows:

    1023
    1023.5
    1023.47 <-- not consistently rounded
    1023.465

    1024
    1024.5
    1024.46 <-- not consistently rounded
    1024.465

    as you can see for toFixed(2), the 0.465 is rounded up to 0.47 when the integer component is 1023 but if the integer component is 1024 its rounded its rounded down to 0.46

    this is causing a lot of problems for me. can somebody tell me why? or how this works or how it can be fixed?

    btw im using firefox 3.6.3

    thanks

  2. #2
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654
    All numbers are floats, so any calculation will give rounding errors
    Use a method like this to give more consistent results
    Code:
    Math.ceil(num*100)/100
    At least 98% of internet users' DNA is identical to that of chimpanzees

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles