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.
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.
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
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.
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.
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));