12

Possible Duplicate:
Convert string to float in Objective-C

I'd like to convert a string to a float.

/* dict is an NSDictionary to load Preferences */ 
NSString *str = [dict objectForKey:@"key"];

This is where I got. Now I'd like to convert the string value (in this case @"32.0f") in a float, where it could be processed by my application. How can I do this?

Community
  • 1
  • 1
Matoe
  • 2,742
  • 6
  • 33
  • 52

2 Answers2

55
CGFloat strFloat = (CGFloat)[str floatValue];
Sid
  • 9,508
  • 5
  • 39
  • 60
  • That's not a floating point number. The floating point primitive has a SINGLE decimal point, like decimal numbers in arithmetics. – Sid May 29 '14 at 14:03
  • **SORRY for previous example** _consider this one_ :: it skips digits after point eg: `NSString * str = @"1.12"; CGFloat strFloat = (CGFloat)[str floatValue];` _// 1.0000_ **please follow this one** http://stackoverflow.com/questions/8011706/objective-c-convert-long-and-float-to-string/23932420#23932420 – asmad May 30 '14 at 11:48
  • Asmad, I pasted your code into Xcode, ran it, and placed a breakpoint and it works properly - http://i.imgur.com/kUXigNn.png – Sid Jun 08 '14 at 03:52
  • Note that this will return 0.0 if the string is not a number. You'll need an additional check to distinguish from a true "0" string input. – Stan James Nov 20 '14 at 20:09
  • @StanJames sure, that's a given. I'm assuming that the user would perform the appropriate checks that should be performed while using NSStrings. – Sid Nov 21 '14 at 14:56
  • This is potentially dangerous because ``CGFloat`` is not guaranteed to be a ``float``, it can also be a ``double``. You may want to do something like the following to be safe: ` NSString *numberAsString = @"2.3"; CGFloat numberAsFloat; if (CGFLOAT_IS_DOUBLE) { numberAsFloat = [numberAsString doubleValue]; } else { numberAsFloat = [numberAsString floatValue]; }` – LinenIsGreat May 12 '15 at 18:59
  • but also obviously I should never be allowed to comment because I have no clue how to use mini-markdown – LinenIsGreat May 12 '15 at 19:02
6

Just pass the message floatValue to the NSString object. NSString::floatValue

Mahesh
  • 34,573
  • 20
  • 89
  • 115