Float Equality Comparison

ID

kotlin.float_equality_comparison

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

CWE:1025, float, precision

Description

Reports == or != used to compare Float or Double values directly.

IEEE 754 floating-point arithmetic introduces rounding errors in almost every computation. Two values that are mathematically equal can differ by a tiny epsilon after addition, subtraction, or type conversion, so == and != comparisons are unreliable and may yield surprising results at runtime.

Rationale

val a = 0.1 + 0.2
val b = 0.3

// Bad — almost certainly false due to rounding
if (a == b) {           // FLAW
    println("equal")
}

// Bad — also unreliable
val x: Float = 1.0f / 3.0f
if (x != 0.333f) {      // FLAW
    println("not equal")
}

// Good — tolerance-based comparison
if (Math.abs(a - b) < 1e-9) {
    println("approximately equal")
}

Remediation

  • Replace a == b with Math.abs(a - b) < epsilon where epsilon is an appropriate tolerance for your domain.

  • Use kotlin.math.abs as the idiomatic Kotlin alternative.

  • For currency or exact decimal arithmetic, use java.math.BigDecimal instead of Float or Double.