0

so wandering... i got this code

double Restant = 0;
Restant = 0.15 - 0.10;

and it gives me 0.049999999 can someone explain me why it does that? and now weird manipulation just before that.

LaurentG
  • 11,128
  • 9
  • 51
  • 66
  • 3
    floating point arithmetic is not accurate –  Mar 11 '14 at 05:01
  • 1
    binary representations of floating point numbers is limited and are inaccurate approximations, doing math on these numbers compounds those inaccuracies. –  Mar 11 '14 at 05:03
  • 1
    0.1 cannot be represented exactly in binary, it would be infinitely repeating so it is approximated. See also [*"Is floating point math broken?"*](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Radiodef Mar 11 '14 at 05:05
  • 1
    Jon Skeet answers:http://stackoverflow.com/questions/1661273/floating-point-arithmetic-not-producing-exact-results-in-java – amudhan3093 Mar 11 '14 at 05:05
  • If you're using floating point, you NEED to understand floating point round-off. (For example, there is no exact representation of either 0.10 or 0.15 in binary floating point.) – keshlam Mar 11 '14 at 05:06
  • Math.round(Restant*100.0)/100.0 – Kanhu Bhol Mar 11 '14 at 05:13

4 Answers4

2

Floating point is not accurate. Use a threshold value to decide if a particular result is "close enough" to be considered equal. E.g.

double EPSILON = 0.0001;
double expected = 0.05;
double actual = 0.15 - 0.10;
boolean isEqual = Math.abs(actual - expected) < EPSILON;

Or, just use Java's BigDecimal class

1

The result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation. Use BigDecimal instead.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
  • BigDecimal is not always the right answer. It's more expensive to process, among other things. Fixed-point (scaled ints) is often preferable. – keshlam Mar 11 '14 at 05:03
1

Unlike fixed point numbers, floating point numbers will some times (safe to assume "most of the time") not be able to return an exact representation of a number. This is the reason why you end up with 11.399999999999 as the result of 5.6 + 5.8.

If you want a fixed point arithmetic, use BigDecimal instead.

Hirak
  • 3,601
  • 1
  • 22
  • 33
0

You should limit the number of fraction digits according to you needs.The following will give the expected result:

System.out.println(String.format("%.2f", Restant));

Jonathan Rosenne
  • 2,159
  • 17
  • 27