开发者

How to compare string with float? in Objective C

开发者 https://www.devze.com 2022-12-25 06:47 出处:网络
How would you? I\'m having problems. Thanks. I\'m currently using if (myString == myfloat) { // do something but this won\'t work

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 bu开发者_StackOverflow社区t this won't work
}

Thanks!


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号