如何比较字符串与浮点数?在目标C中

0 string floating-point comparison objective-c

你好吗?我有问题.谢谢.

我正在使用

if (myString == myfloat) {
// do something but this won't work
}
Run Code Online (Sandbox Code Playgroud)

要么

if ([myString == myFloat]) {
// do something but this won't work
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

ken*_*ytm 6

==操作不仅使当两个类型是兼容的,这是不是字符串和浮点数的情况下感.一方必须明确转换为另一方.

您可以将NSString转换为float:

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

或者将float转换为NSString(非常不寻常):

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