-2

I had a problem in some process in my web, after a time looking for a problem, I can detect what happened, now I had a question, why it is happening?.

Example: Below there is a code example:

function DoSomething(number, divisor){
var result = number % divisor;
var minimumAllowed = 0;
  if(result == minimumAllowed){
          .... Do stuff
  }
}

When the code passes in the parameters, number = 1000 and divisor = 0.2, I could reproduce the problem.

Here is the problem in mozilla console:

1000 % .2 = 0.1999999999999445
1000 / .2 = 5000

I think 1000 % .2 = 0, not 0.1999999999999445 so 1000 / .2 is 5000.

Thanks alot for explainme.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
mmadrigal
  • 95
  • 1
  • 8

1 Answers1

1

The issue is not in javascript, it's in the way the floating point numbers are handled by the processor.

Basically every floating point operation comes with a cost of a math error, ususally very small, when you add, multiply, et cetera, but it become really painful once you need for instance check whether something is equal, like in this case.

If you try your code with integer values (try 10000 % 2), you should get a correct answer.

Marandil
  • 1,042
  • 1
  • 15
  • 31
  • 1
    *"Basically every floating point operation comes with a cost of a math error"* ... is not true. *Some* operations are inexact, but if all numbers involved have an exact binary representation then there's no error. – JJJ Sep 11 '15 at 23:02
  • By "operation" I mean "operation" - addition, subtraction, multiplication, etc. not every combination of every possible input and operand. – Marandil Sep 11 '15 at 23:03
  • I would say that *none* of the operations has an "error".The *representation of values* can have (precision) errors (which then propagates). – Felix Kling Sep 11 '15 at 23:06