#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    5
    Rep Power
    0

    When I add Doubles, unexpected result!


    When I add 3 doubles (1.1,2.1,3.1) , I get 6.300000000000001

    This is obviously a rookie error - could someone enlighten me please?

    Code:
    double x,y,z,total;
        x = Double.parseDouble(JOptionPane.showInputDialog("Please enter a number"));
        y = Double.parseDouble(JOptionPane.showInputDialog("Please enter a number"));
        z = Double.parseDouble(JOptionPane.showInputDialog("Please enter a number"));
        total = x + y + z;
         System.out.println(total);
        }
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Feb 2004
    Location
    Mobile, Alabama
    Posts
    4,024
    Rep Power
    1286
    You haven't done anything wrong. The reason for the result is that there are some decimal numbers which cannot be converted exactly into binary.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    5
    Rep Power
    0
    Originally Posted by bullet
    You haven't done anything wrong. The reason for the result is that there are some decimal numbers which cannot be converted exactly into binary.
    Thanks - is rounding the only solution? Obviosuly in many scenarios, the total I came up with would be unacceptable.
  6. #4
  7. Wiser? Not exactly.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    May 2001
    Location
    Bonita Springs, FL
    Posts
    5,966
    Rep Power
    4035
    Originally Posted by basil54
    Thanks - is rounding the only solution? Obviosuly in many scenarios, the total I came up with would be unacceptable.
    There are generally two workarounds to floating point issues.
    1) Do your work as plain integers and then divide and round at the last moment. For example, the above would instead be:
    Code:
    (11+21+31)/10
    or
    2) Use an arbitrary precision math library designed for exact number representation. I don't really know Java so I can't offer a specific suggestion as to what to use for this, but a quick google suggests the java.math.BigDecimal object is a possibility.
    Recycle your old CD's, don't just trash them



    If I helped you out, show some love with some reputation, or tip with Bitcoins to 1N645HfYf63UbcvxajLKiSKpYHAq2Zxud

IMN logo majestic logo threadwatch logo seochat tools logo