0

So, I made this lines of code to return 10% of the value in the parameter. For example, if the value being given is 7, the code should return 0.7. But it is returning 0.7000000000000001. Any thoughts why? The code is below:

    public double calculateDiscount(double price){
        double discount;
        discount = price*0.10;
        return discount;
    }

I'm using eclipse IDE, and using the debug, I didn't find anything weird, the multiplication is simply returning that huge number.

PS.: I know that I can return only two decimal cases, but I want to know whats going on.

PPS.: Using /10 instead of *0.10 works just fine. But, as I said, I want to know why.

  • 1
    double and float (in almost any language) don't represent exact floating point numbers, have a look at this answer: http://stackoverflow.com/questions/6459335/accuracy-of-double-precision-multiplication-in-java – morgano Jul 03 '14 at 04:54
  • It's almost as if certain numbers can't be represented with full precision. Weird. I wonder if googling for this would bring up a case of anyone ever having this problem before.. ;) – Ingo Bürk Jul 03 '14 at 04:54
  • Floating point representation is not mathematically accurate. Machine numbers aren't decimal fractions. – laune Jul 03 '14 at 04:56
  • @IngoBürk Google indeed. – laune Jul 03 '14 at 04:57
  • The duplicate question I marked is for Perl, but the answer is identical. Floating point _cannot_ represent most real numbers accurately. – Jim Garrison Jul 03 '14 at 04:59
  • 1
    Serious financial calculation must avoid double and float. And be on your guard with all other numerical mathematical algorithms. – laune Jul 03 '14 at 05:02
  • 3
    How is it that your first intuition is that Java, which is an almost 20 year old, established programming language, would be to blame? – Sotirios Delimanolis Jul 03 '14 at 05:04
  • 1
    @SotiriosDelimanolis - It is what they call "the wisdom of youth". Anything that is older than I am is by definition wrong :-) – Stephen C Jul 03 '14 at 05:29
  • @JimGarrison why link to obscure perl-related and formatting-related question instead of practically canonical question about floating-point arithmetic? – Oleg Estekhin Jul 03 '14 at 11:58
  • @OlegEstekhin OK, you have a valid point. The canonical reference is [What Every Computer Scientist Should Know About Floating Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Jim Garrison Jul 03 '14 at 15:34

1 Answers1

0

If you really care about precision, may be you want to use java.math.BigDecimal.

See more in How to Use Java BigDecimal: A Tutorial.

Paul Vargas
  • 41,222
  • 15
  • 102
  • 148