6

I want to be able to test if zero is positive or negative in swift.

let neg: CGFloat = -0
let pos: CGFloat = +0

if pos == neg {
    // this gets executed, but I don't want this
}

The code above does not work like I need it to. Can someone help me?

Sep Roland
  • 33,889
  • 7
  • 43
  • 76
swift-lynx
  • 3,219
  • 3
  • 26
  • 45

2 Answers2

7

There are “negative zero” and “positive zero” floating point numbers. You can disambiguate them by checking the .sign property, but they (intentionally) compare as equal:

let neg: CGFloat = -0.0
let pos: CGFloat = +0.0

print(neg.sign) // minus
print(pos.sign) // plus
print(neg == pos) // true

if (neg == pos && neg.sign == pos.sign) {
    // This is not executed.
}

Note that you have to use floating point literals ("-0.0" or "+0.0") in the initialization. The integer literals ("+0", "-0") are equal and converted to positive zero.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

Basically, from the ordinary arithmetic point view both neg and pos are identical zeros, therefore if pos == neg is true.

However, when it comes to representing a floating-point number, CGFloat has sign property as FloatingPointSign enum:

minus if the sign bit of self is set, and plus otherwise. Implements the IEEE 754 sign bit operation.

Therefore, your if-statement would be:

if neg.sign == pos.sign { } // false
Ahmad F
  • 30,560
  • 17
  • 97
  • 143