Dylan Wheeler
Dylan Wheeler

Reputation: 7074

Java Glitch? Subtracting numbers?

Is this a glitch in Java?

I go to solve this expression: 3.1 - 7.1

I get the answer: -3.9999999999999996

What is going on here?

Upvotes: 5

Views: 7364

Answers (5)

Kevin Carrasco
Kevin Carrasco

Reputation: 1052

A great explanation can be found here. http://www.ibm.com/developerworks/java/library/j-jtp0114/

Floating point arithmetic is rarely exact. While some numbers, such as 0.5, can be exactly represented as a binary (base 2) decimal (since 0.5 equals 2-1), other numbers, such as 0.1, cannot be. As a result, floating point operations may result in rounding errors, yielding a result that is close to -- but not equal to -- the result you might expect. For example, the simple calculation below results in 2.600000000000001, rather than 2.6:

double s=0;

for (int i=0; i<26; i++)
    s += 0.1;
System.out.println(s); 

Similarly, multiplying .1*26 yields a result different from that of adding .1 to itself 26 times. Rounding errors become even more serious when casting from floating point to integer, because casting to an integral type discards the non-integral portion, even for calculations that "look like" they should have integral values. For example, the following statements:

  double d = 29.0 * 0.01;
  System.out.println(d);
  System.out.println((int) (d * 100));

will produce as output:

 0.29
  28  

which is probably not what you might expect at first.

See the provided reference for more information.

Upvotes: 10

r0ast3d
r0ast3d

Reputation: 2637

Automatic type promotion is happening and that is the result.

Here is some resource to learn.

http://docs.oracle.com/javase/specs/jls/se5.0/html/conversions.html

The next step would be is to learn to use formatters to format it to the given precision / requirements.

Upvotes: 1

matsev
matsev

Reputation: 33749

As mentioned by several others you cannot count on double if you would like to get an exact decimal value, e.g. when implementing monetary applications. What you should do instead is to take a closer look at BigDecimal:

BigDecimal a = new BigDecimal("3.1");
BigDecimal b = new BigDecimal("7.1");
BigDecimal result = a.subtract(b);
System.out.println(result);      // Prints -4.0

Upvotes: 2

ratchet freak
ratchet freak

Reputation: 48196

rounding errors in floating points

same way that 3 * 0.1 != 0.3 (when it's not folded by the compiler at least)

Upvotes: 1

AshotN
AshotN

Reputation: 413

Computers are 100% so in the math world that is correct, to the average person it is not. Java cant have a error on a specific number as it is just code that runs the same way but has a different input!

P.S. Google how to round a number

Upvotes: 1

Related Questions