The result of integer-returning built-in API should not be compared with a float number

  • BAD_COMPARISON_WITH_FLOAT
  • Error
  • Medium
  • No tags

This rule applies when the result of a built-in API that returns an integer is compared with a float number.

Depending on the comparison operator, the following unintended behaviors may occur when the integer is compared with a float:

  1. ==, ===, !=, !==: The comparison result is always false
  2. <, <=, >, >=: The comparison becomes imprecise

Noncompliant Code Example

View with compliant examples side by side
// Example 1
if (parseInt(x) == 0.1) { // BAD_COMPARISON_WITH_FLOAT alarm because the comparison result is always false.
    doSomething(x);
}

// Example 2
let rounded = Math.round(x);
if (rounded < 4.2) { // BAD_COMPARISON_WITH_FLOAT alarm because the comparison is imprecise.
    doSomething(x, rounded);
}

Compliant Code Example

View with noncompliant examples side by side
// Example 1
if (parseFloat(x) == 0.1) {
    doSomething(x);
}

// Example 2
let rounded = Math.round(x);
if (x < 4.2) {
    doSomething(x, rounded);
}

Version

This rule was introduced in DeepScan 1.31.0.