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
2010-01-05 20:57:35
beat me to it =)
Stephen Canon
2010-01-05 21:01:43
+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
2010-01-05 21:26:36
+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
2010-01-05 21:30:52
My point is `NSTextField` does not respond to the method `text`. `stringValue` yes, `text` no ;)
ctshryock
2010-01-05 21:50:24
Apparently this is an iPhone SDK question and UITextField does in fact have a 'text' method. My mistake
ctshryock
2010-01-06 01:21:06