Search code examples
objective-cnsrangenscharacterset

rangeOfCharacterFromSet: with numeric set


Hoi!

I got a NSString which looks something like this: "$1.00". Always a currency symbol with a value.

I format this string to remove the symbol and any non-decimal characters with str = [str stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]. This leaves me with "1.00".

Now I'm checking with [str rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location == NSNotFound if there are any non-decimal characters in there. Since I removed all of them before this should return YES. But I am getting NO with the location pointing to the decimal separator.

Does anyone have an idea what is going wrong here? Maybe it's a stupid mistake but I can't find it...

Additional info

I just found a similar issue: I got a string "$20,000.00" and use execute this code:

NSCharacterSet *nonNumbersSet = [[NSCharacterSet characterSetWithCharactersInString:[NSString stringWithFormat:@"0123456789."]] invertedSet];

NSString* numberString = [_value stringByTrimmingCharactersInSet:nonNumbersSet];

The result is "20,000.00". Those methods seem to have a problem with those characters in general. If anyone has a solution to this please tell me.


Solution

  • Okay, I just found the solution. I just had a wrong understanding of stringByTrimmingCharactersInSet:. It doesn't remove all characters, only the ones on both ends.