SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Apr 2007
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Javascript floats error?!

    Please consider the following code:

    var first = 345.50 + 0.001;
    var second = 345.51 + 0.001;
    var third = 345.52 + 0.001;
    var fourth = 345.53 + 0.001;
    var fifth = 345.54 + 0.001;

    Why is the results of the second, third and fourth so very different from the first and fifth??

  2. #2
    SitePoint Member
    Join Date
    Apr 2007
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    For the lazy, the results come out as:

    First: 345.501
    Second: 345.51099999999997
    Third: 345.52099999999996
    Fourth: 345.53099999999995
    Fifth: 345.541

    The big thing is, I want to cut the float down to two decimals. The normal divide-by/multiply-by method doesn't work the way I want it to, as it display the number "345.50" as "345.5"

  3. #3
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Floating-point numbers are not exact, due to the way they are represented in memory. There'll almost always be rounding errors.

    Try
    Code:
    var first = new Number(345.50 + 0.001);
    alert(first.toFixed(2));
    Birnam wood is come to Dunsinane

  4. #4
    SitePoint Member
    Join Date
    Apr 2007
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Seems to work much better!
    Didn't know about the .toFixed() method. Thanks!


Bookmarks

Posting Permissions

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