-4

Was debugging a piece of code and found this strange issue .

On addition of two double variables 0.0040 and 0.0005, Java return me the result as "0.0045000000000000005"

Here's my piece of code :-

    public static void main(String[] args) {
    double a = 0.0040  ;
    double b = 0.0005;
    double result = a+b ;
    System.out.println(result);
}

Output : 0.0045000000000000005

The output is correct if I give value between 0.0041 to 0.0044 for variable "a" . However, If I give the value to variable "a" as 0.0045 it gives output as "0.004999999999999999".

Help needed !!

BitingBugz
  • 13
  • 5
  • 4
    Search needed! Floating point math! Always happens! –  Feb 16 '15 at 13:51
  • Related - http://stackoverflow.com/questions/322749/retain-precision-with-doubles-in-java – Deepak Bala Feb 16 '15 at 13:51
  • 1
    If you look around a bit, you'll find that Stack Overflow gets roughly eleventy billion questions a day from people like you who don't understand that floating point math isn't exact. It makes me wonder why schools don't teach this simple concept on day one. – Paul Tomblin Feb 16 '15 at 13:53
  • The oldest one (or nearly the oldest one) in the book... – meskobalazs Feb 16 '15 at 13:55

2 Answers2

3

You can do exact floating point arithmetic in Java using BigDecimal.

Here is an example:

BigDecimal a = new BigDecimal("0.0040");
BigDecimal b = new BigDecimal("0.0005");
BigDecimal sum = a.add(b);

Also note that BigDecimal and BigInteger (the same for integers) are immutable.

MinecraftShamrock
  • 3,504
  • 2
  • 25
  • 44
2

It's because of floating point numbers, they lose precision and cause the problem you are seeing. Rather use BigDecimal for precision

GoofyHTS
  • 263
  • 1
  • 6
  • 15
  • Is it not possible by using double ? Can you give me the same example in BigDecimal – BitingBugz Feb 16 '15 at 13:54
  • I suggest you have a look at the other question (the one marked as duplicate at the top) as it as a much more in-depth answer. Regarding examples of BigDecimal, googling "BigDecimal tutorial" would return a lot of results, here's one such site: http://www.mkyong.com/java/how-do-calculate-monetary-values-in-java-double-vs-bigdecimal/ – GoofyHTS Feb 16 '15 at 13:59