This product is not supported for your selected Datadog site. ().
Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

Metadata

ID: swift-code-style/float-equality

Language: Unknown

Severity: Warning

Category: Best Practices

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

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
        }
    }    
}
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

class BankAccount {
    var myValue: Float

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

}
class BankAccount {

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

    }    
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains