views:

447

answers:

2

How do I convert the text inside of a TextField to a float in Objective-C?

+5  A: 

float myFloat = [[myTextField text] floatValue];

Edit: technically the most proper way to do this would be to use an NSNumberFormatter, since that will return a nil NSNumber if it can't parse the string properly, whereas floatValue will just return 0.0 for a malformed string. But floatValue is usually adequate for most purposes.

Dave DeLong
beat me to it =)
Stephen Canon
+4  A: 

If it's an NSTextField you call floatValue on the actual object, not on what's returned from text. NSTextField does not have a text method.

float myFloat = [myTextField floatValue];

ctshryock
+1 good point. You can also do: `float myFloat = [[myNSTextField stringValue] floatValue];`. I think (semantically) it makes more sense to get the floatValue from the string, because I don't think it makes sense to call `floatValue` on a textField. Do you convert a textfield to a float, or do you convert the contents of a textfield to a float? This is just my pedantic opinion, but I think it makes more sense. :)
Dave DeLong
My point is `NSTextField` does not respond to the method `text`. `stringValue` yes, `text` no ;)
ctshryock
Apparently this is an iPhone SDK question and UITextField does in fact have a 'text' method. My mistake
ctshryock