Results 1 to 4 of 4
  1. #1
    GPB
    GPB is offline Member
    Join Date
    Feb 2010
    Posts
    20
    Rep Power
    0

    Default double a * double b = weird output

    Java Code:
        public void test () {
            double a = 0.2, b = 3;
            System.out.println(a*b);
        }
    Why does this output 0.6000000000000001 ? :confused:
    I need it to output 0.6

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,019
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by GPB View Post
    Java Code:
        public void test () {
            double a = 0.2, b = 3;
            System.out.println(a*b);
        }
    Why does this output 0.6000000000000001 ? :confused:
    I need it to output 0.6
    Imagine the following 'game': you have the numbers 1/2, 1/4, 1/8 ... 1/2^52. Given an arbitrary number d select the numbers (at most once) and add their values and try to make that sum equal to d; if you want you can multiply or divide your sum by two as many times as you want. That's how IEEE754 floating point numbers work. You can't make the number 0.2 with that 'game'.

    An analogy in decimal: you can't make the number 1/3 given a finit number of decimals. That's why you get that 'funny' result. The cure: for representations of those floating point numbers that 'look better' have a look at the DecimalFormat class.

    kind regards,

    Jos

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    19

    Default

    And if you need accurate decimal representations (say for finance stuff) use BigDecimal.

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

Similar Threads

  1. Weird output
    By gandalf5166 in forum New To Java
    Replies: 2
    Last Post: 02-28-2010, 09:17 PM
  2. Seriously weird output
    By gandalf5166 in forum Java Applets
    Replies: 4
    Last Post: 02-27-2010, 04:16 AM
  3. Check if double is double
    By marshalthrone in forum New To Java
    Replies: 8
    Last Post: 09-30-2009, 02:51 PM
  4. Replies: 5
    Last Post: 03-21-2009, 09:32 PM
  5. Double.valueOf() vs Double.parseDouble()
    By greenbean in forum New To Java
    Replies: 10
    Last Post: 01-12-2009, 08:39 AM

Posting Permissions

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