3

so I want to convert NSString to double. I found the following example:

NSString * s = @"1.5e5";
NSLog(@"%lf", [s doubleValue]);

It works but if doubleValue cannot convert the string to double it simply returns 0.0 which is not what I need. I need some method that tries to convert a string representation of double to double and if indicate somehow if it can't be converted. c# has an excellent method

double d;
boolean Double.TryParse(str, out d)

Is there any method similar to the above one in Objective C? or maybe it's better to use regex? however, i don't really know how to do that.

tesla
  • 77
  • 1
  • 5
  • Another example of people thinking that regex is the ultimate magic solution for everything and that it brings world peace... –  Oct 12 '12 at 19:50
  • By the way, what you're doing is **undefined behavior.** I won't be surprised if it printed out the correct value if you used `%lf` instead of `%f` (which is for `float`s and not for `double`s...) –  Oct 12 '12 at 19:52
  • @H2CO3: According to [String Programming Guide/Format Specifiers](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html), `%f` works with `float` and `double` when formatting. Only for scanning you have to differentiate. – Martin R Oct 12 '12 at 19:58
  • @MartinR Strange. Upper on the same page it's written that NSString format specifiers support everything `printf()` does - and for printf, `%f` is for floats and `%lf` is for doubles, and using them interchangeably is undefined behavior. –  Oct 12 '12 at 20:02
  • @H2CO3: I am not an expert on this, but http://stackoverflow.com/questions/4264127/correct-format-specifier-for-double-in-printf states that `%f` can be used for `double`. That is also what I understand from http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html. – Martin R Oct 12 '12 at 20:09
  • @MartinR Bingo! Asked the poster of the answer you linked and he explained how default type promotion with variadic functions works. You're right. –  Oct 12 '12 at 20:16

1 Answers1

9

You can use the NSScanner class:

NSString *s = @"1.5e5";
NSScanner *scanner = [NSScanner scannerWithString:s];
double d;
BOOL success = [scanner scanDouble:&d];

If you want to ensure that the entire string has been scanned (no extra characters after the number), use

BOOL isAtEnd = [scanner isAtEnd];
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382