NSString to float…what happens if NSString is not numerical and contains alphanumeric characters?

我只是一个虾纸丫 提交于 2019-12-06 19:23:25

Read the documentation.

Return Value

The floating-point value of the receiver’s text as a float, skipping whitespace at the beginning of the string. Returns HUGE_VAL or –HUGE_VAL on overflow, 0.0 on underflow.

Also returns 0.0 if the receiver doesn’t begin with a valid text representation of a floating-point number.

The best way to figure out the return value is to check the return value yourself. You can create a small program and save it as a file with a .m extension. Here's a sample:

// floatTest.m
#import <Foundation/Foundation.h>

int main() {
    NSString *sample = @"1sa34hjh#@";
    float floatsample = [sample floatValue];
    printf("%f", floatsample);
    return 0;
}

Compile it on the command-line using clang and linking with the Foundation framework.

clang floatTest.m -framework foundation -o floatTest

Then run the executable and see the output.

./floatTest

The printed value is 1.000000. So to answer your question, if the string starts with a number, then the number portion of the string will be taken and converted to float. Same rules as above apply on overflow or underflow.

If creating the files seems like a hassle, you might like this blog post on minimalist Cocoa programming.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!