1

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.

  • 1
    "This leaves me with 1.00". Does it? `'.'` is not a decimal digit. – trojanfoe Apr 06 '16 at 09:00
  • In some regions it's the decimal separator which should be included in the decimal character set as far as I know. But I think those methods have problems with punctuation in general. I just found a similar issue, I will add additional info. – Peter Meinhardt Apr 06 '16 at 09:11
  • The documentation for `decimalDigitCharacterSet` does not mention `.`. – trojanfoe Apr 06 '16 at 09:11
  • Then why is it not removed by the first execution? I also tried to use a custom character set with all numbers and the decimal separator from NSNumberFormatter. This also didn't work. – Peter Meinhardt Apr 06 '16 at 09:17
  • Oh and also the documentation says: "These characters include, for example, the decimal digits of the Indic scripts and Arabic." – Peter Meinhardt Apr 06 '16 at 09:19
  • And what does that mean? – trojanfoe Apr 06 '16 at 09:20
  • Oh, I read it wrong... It's digits, not separators^^ Still the behavior isn't what it should be. If it's only the digits, the dot should've been removed. – Peter Meinhardt Apr 06 '16 at 09:20

2 Answers2

0

This may help:

NSMutableCharacterSet *digitsAndDots = [NSMutableCharacterSet decimalDigitCharacterSet]; 
[digitsAndDots addCharactersInString:@"."]; 
NSCharacterSet *notDigitsNorDots = [digitsAndDots invertedSet];
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98
0

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.