﻿# V7036\. Suspicious precise comparison\. Consider using a comparison with defined precision\.

The analyzer has detected a code fragment where the \=\=, \=\=\=, \!\=, or \!\=\= operators are used to compare floating\-point numbers\. Such code may be erroneous\. 

The example:

```cpp
let result = x * y;
if (result === 0.1) { // <= 
  ....
}
```

The condition `result === 0.1` will almost never be true\. The reason is that JavaScript, as per the [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) standard, can only represent the number 0\.1 as its closest possible approximation: `0.1000000000000000055511151231257827021181583404541015625`\. It is very unlikely that arithmetic operations will produce exactly the same result\.

To fix this, compare the difference between the values against a defined precision: 



```cpp
let result = x * y;
if (Math.abs(result - 0.1) < Number.EPSILON) { // <= 
  ....
}
```

This approach works well for numbers of small orders of magnitude \(for more details on this issue, see the official documentation: [Number\.EPSILON](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON)\)\. A broader option is to compare both the absolute and relative errors between two numbers:

```cpp
function nearlyEqual(a, b,
                     relEpsilon = 4 * Number.EPSILON,
                     absEpsilon = Number.EPSILON
) {
  if (a === b) {
    return true;
  }

  if (Number.isNaN(a) || Number.isNaN(b)) {
    return false;
  }

  let difference = Math.abs(a - b);

  if (difference <= absEpsilon) {
    return true;
  }
  
  let maxAbsoluteValue = Math.max(Math.abs(a), Math.abs(b)); 
  return difference / maxAbsoluteValue <= relEpsilon;
}

let result = x * y;
if (nearlyEqual(result, 0.1)) { 
  ....
}
```