---
title: Floating point values should not be tested for equality
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Floating point values should not be tested for equality
---

# Floating point values should not be tested for equality

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site). ().
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `swift-code-style/float-equality`

**Language:** Swift

**Severity:** Warning

**Category:** Best Practices

## Description{% #description %}

This rule flags instances where floating point values are tested for equality using `==` or `!=`. Due to the inherent precision limitations of floating point representation, direct equality comparisons can lead to unreliable or unexpected results. Small rounding errors or differences in representation mean that two values that are conceptually equal might not match exactly when compared.

It is important to avoid direct equality tests on floating point numbers to prevent subtle bugs, especially in financial calculations, scientific computations, or any domain where precision matters. Instead, comparisons should be done using a tolerance or range check, ensuring the values are "close enough" rather than exactly equal.

## Non-Compliant Code Examples{% #non-compliant-code-examples %}

```swift
class BankAccount {

    func withdraw(myValue: Float) {
        if myValue == 0.42 {
            //something
        }

        if myValue != 0.42 {
            //something else
        }

        if 0.42 == myValue {
            //something
        }

        if 0.42 != myValue {
            //something else
        }
    }    
}
```

```swift
class BankAccount {
    var myValue: Float

    func something() {
        if myValue == 0.42 {
            //something
        }

        if myValue != 0.42 {
            //something else
        }

        if 0.42 == myValue {
            //something
        }

        if 0.42 != myValue {
            //something else
        }
    }

}
```

## Compliant Code Examples{% #compliant-code-examples %}

```swift
class BankAccount {
    var myValue: Float

    func something() {
        if myValue > 0.41 && myValue < 0.43 {
            //something
        }
    }

}
```

```swift
class BankAccount {

    func withdraw(myValue: Float) {
        if myValue > 0.41 && myValue < 0.43 {
            //something
        }

    }    
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 