1

if NSString sample = @"1sa34hjh#@";
Float 64 floatsample = [sample floatValue];

what happens? what does floatsample contain?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Namratha
  • 16,630
  • 27
  • 90
  • 125

1 Answers1

6

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.

Anurag
  • 140,337
  • 36
  • 221
  • 257
  • thank you very much! :) next time i'll post only if i don't understand the documentation. One question-if it returns 0.0 both times, we can't differentiate what the issue is, right? – Namratha Feb 11 '11 at 05:00
  • your input actually returns `1.0`, not `0.0`. But to determine if the given is a valid floating point number without any junk characters, use `scanFloat:` in [NSScanner](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSScanner_Class/Reference/Reference.html). Some good folks have already done this for us for many languages at [rosettacode.org](http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Objective-C). – Anurag Feb 11 '11 at 05:07
  • "your input actually returns 1.0, not 0.0" Could you please explain that? I didn't fully understand. – Namratha Feb 15 '11 at 09:26
  • @Namratha - since `"1sa34hjh#"` starts with a valid number - `1`, that part of the string is parsed and everything else is ignored. If, however, the string did not start with a number, for ex., `"a123.45"`, then `0` would have been returned. – Anurag Feb 21 '11 at 08:03