David
David

Reputation: 1

How to compare string with float? in Objective C

How would you? I'm having problems. Thanks.

I'm currently using

if (myString == myfloat) {
// do something but this won't work
}

OR

if ([myString == myFloat]) {
// do something but this won't work
}

Thanks!

Upvotes: 0

Views: 984

Answers (1)

kennytm
kennytm

Reputation: 523304

The == operator only makes sense when the two types are compatible, which is not the case between strings and floats. One side must be explicitly converted to the other.

You may convert the NSString into a float:

if ([myString floatValue] == myFloat) {
  // Note: Use "fabs(a - b) < epsilon" to avoid inequality due to precision lost.

or convert the float into an NSString (very unusual):

if ([myString isEqualToString:[NSString stringWithFormat:@"%g", myFloat]]) {
  // Note: make sure the string is encoded as "%g" as well.

Upvotes: 6

Related Questions