开发者

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜