-1

Possible Duplicate:
Java floating point arithmetic

What is special about this double math in Java? I would expect the answer of .9 - 1 to be -0.1, however the response is -0.09999999999999998

double a = 0.9;
double b = 1.0;
double c = a - b;
System.out.println(c);
>>-0.09999999999999998
Community
  • 1
  • 1
P. Deters
  • 747
  • 2
  • 8
  • 18
  • 3
    Mandatory read : http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html – Mike Kwan Aug 04 '11 at 14:01
  • 4
    The float questions will never end!!!!! http://stackoverflow.com/questions/61872/use-float-or-decimal-for-accounting-application-dollar-amount – Joe Aug 04 '11 at 14:01

5 Answers5

2

Yet another question about precision of doubles. Doubles have limited precision. Not all numbers can be represented precisely!

Armen Tsirunyan
  • 125,569
  • 56
  • 315
  • 427
2

Floating point precision is difficult for computers. See this article and Retain precision with double in Java for details

For accurate floating point arithmetic use BigDecimal

Community
  • 1
  • 1
Nivas
  • 17,720
  • 4
  • 58
  • 75
1

The value 0.9 cannot be represented exactly in binary form.

Atreys
  • 3,693
  • 1
  • 16
  • 27
1

double is not exact. this is the nearest number that can be represented by double.

try to read what every programmer should know about floating point arithmetic.

amit
  • 172,148
  • 26
  • 225
  • 324
1

There are an infinite number of numbers between any two values.

There are a finite number of memory bits on any computer. So any way we chose to represent floating point numbers will never be exact.

Mark Bolusmjak
  • 22,826
  • 10
  • 70
  • 122
  • actually, even if there were infinite but countable memory, it still won't be enough, since there are uncountable number of elements between each two numbers. [so any turing machine will never be able to precisely represent a real number] – amit Aug 04 '11 at 14:06