Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4

Thread: round off error

  1. #1
    New Coder
    Join Date
    May 2004
    Posts
    48
    Thanks
    5
    Thanked 0 Times in 0 Posts

    round off error

    Math.log(1000) / Math.log(10) = 3, not 2.9999999999996

    How do I make Javascript acknowledge this, even if I must lose the final digit?


    I've tried this:
    Code:
                g = Math.log(a)/Math.log(b); 
                g = g * 10000000000000;
                g = g + +0.0000000000005;
                g = parseInt(g);
                g = parseFloat(g / 10000000000000);
    which is typical code for rounding. But it didn't work. I lost the final 6, but I still get a string of 9s.
    Thanks!

  • #2
    New to the CF scene
    Join Date
    Sep 2008
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Code:
    Math.round(Math.log(1000)/Math.log(10))

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,735
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Quote Originally Posted by grink View Post
    Code:
    Math.round(Math.log(1000)/Math.log(10))
    Math.round() rounds to the nearest integer - OK here.

    If you want to round a decimal number to (say) two decimal places:-

    Code:
    x = 3.7646386370435;
    x = x * 100;  // take it up two places
    x = Math.round(x);  // do the round
    x = x/100;  // take it back down two places
    alert (x);
    or

    Code:
    x = 3.764638638670435;
    x = x.toFixed(2) * 1;  // toFixed() converts to a string so multiply by 1 to revert to number if further processing is required.  Omit if x to display only.
    alert (x);

    At least once per year, some group of scientists will become very excited and announce that whatever they announced last year about global warming is wrong.
    Last edited by Philip M; 09-13-2008 at 08:22 AM.

  • Users who have thanked Philip M for this post:

    tony873004 (09-14-2008)

  • #4
    New Coder
    Join Date
    May 2004
    Posts
    48
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Your first method works perfectly. Thanks!


  •  

    Posting Permissions

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