NSString to float...what happens if NSString is not numerical and contains alphanumeric characters?
if
NSString sample = @"1sa34hjh#@";
Float 64 floatsample = [sample floatValue];开发者_如何学JAVA
what happens? what does floatsample contain?
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.
精彩评论