-1

I am doing the comparison:

 else if([change doubleValue] == 0 && indexPath.row == sectionRows - 1)

how can I check for the case where [change doubleValue] doesn't return anything?

ThomasW
  • 16,981
  • 4
  • 79
  • 106
Sheehan Alam
  • 60,111
  • 124
  • 355
  • 556
  • 1
    How can it not return anything? – BoltClock Sep 03 '11 at 04:47
  • 3
    What do you mean, "doesn't return anything"? Do you mean if `change` doesn't understand the `doubleValue` message? – Jon Reid Sep 03 '11 at 04:47
  • 1
    possible duplicate of [How to convert an NSString into an NSNumber](http://stackoverflow.com/questions/1448804/how-to-convert-an-nsstring-into-an-nsnumber) – Dave DeLong Sep 03 '11 at 06:05
  • 1
    Isn't it dangerous to compare floating point numbers with the `==`-operator? –  Sep 03 '11 at 07:31

2 Answers2

4

There's no way the doubleValue method goes without returning anything. The least value you can check for is 0. The following are the cases the doubleValue returns 0.

  1. The string doesn't contain a valid numerical value.
  2. The string is nil.
  3. The string actually contains @"0".

Checking for a valid number
Use NSPredicate to test if the string contains a numerical value.

NSString *str = @"sfas";
NSString *regx = @"(-){0,1}(([0-9]+)(.)){0,1}([0-9]+)";
NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regx];
BOOL isAValidNumber = [test evaluateWithObject:str];
EmptyStack
  • 51,274
  • 23
  • 147
  • 178
  • How can I check if the string doesn't contain a valid numerical value? – Sheehan Alam Sep 03 '11 at 05:10
  • Use a NSPredicate test. Updated the answer. – EmptyStack Sep 03 '11 at 05:25
  • 5
    What if the user's in a locale where `,` is used as the decimal separator? Using an `NSNumberFormatter` is the superior option. – Dave DeLong Sep 03 '11 at 06:07
  • @Dave DeLong, Yeah. That's a good point. For that reason you down voted this answer? I don't think that is a major reason for this answer to be down voted? – EmptyStack Sep 03 '11 at 06:18
  • @Dave DeLong, My answer is just an simple example. You have to tweak to fit your needs. You should not expect an answer to be 100% perfect. – EmptyStack Sep 03 '11 at 06:20
  • Also negative numbers will fail with this example predicate. – Nick Moore Sep 03 '11 at 07:14
  • Your new regex recognizes "-." (assuming you meant "\." in the middle and not "."). It requires numbers to have a decimal point, so you can't recognize "42". It also requires numbers to have a negative sign. It also won't recognize scientific notation ("4.2e1"), or numbers grouped into thousands (1,234.5 or 1.234,5). I down voted because while using a regex can work, it's extremely error-prone. Plus, the Foundation framework already has code that does this for you. Why re-invent the wheel? – Dave DeLong Sep 03 '11 at 15:33
2

see NSScanner


justin
  • 104,054
  • 14
  • 179
  • 226