Este producto no es compatible con el sitio Datadog seleccionado. ().
Esta página aún no está disponible en español. Estamos trabajando en su traducción.
Si tienes alguna pregunta o comentario sobre nuestro actual proyecto de traducción, no dudes en ponerte en contacto con nosotros.

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

Integraciones sin problemas. Prueba Datadog Code Security