This product is not supported for your selected Datadog site. ().
このページは日本語には対応しておりません。随時翻訳に取り組んでいます。
翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください

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

シームレスな統合。 Datadog Code Security をお試しください