Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumberFormatter, how to remove blank spaces in currency symbol

I'm having some values that I need to format into a currency string. It seems that when using NSNumberFormatter to format an amount, the resulting currency string will contain one or more blank spaces.

For instance using the following piece of code to format @"1000" into the European currency format will result in returning @"1,000,00 €". Note the blank space before the currency symbol.

NSNumberFormatter *tempNumberFormatter = [[NSNumberFormatter alloc] init];
 [tempNumberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
 [tempNumberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
 [tempNumberFormatter setLocale:[NSLocale currentLocale]];
 [tempNumberFormatter setGeneratesDecimalNumbers:YES];
 [tempNumberFormatter setMaximumFractionDigits:2];
 [tempNumberFormatter setMinimumFractionDigits:2];
 [tempNumberFormatter setAlwaysShowsDecimalSeparator:YES];

 NSString *value = @"1000";

 NSNumber *number = [NSNumber numberWithFloat:[value doubleValue]];

 NSString *result = [tempNumberFormatter stringFromNumber:number];

 [tempNumberFormatter release];

 // result  = 1.000,00 € 

I first thought to solve this easily by just filtering the spaces out of the string but for some reason this does not work, the following piece of code is not doing what I was expecting:

[result replaceOccurrencesOfString:@" " withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [result length])];

Is there any way using NSNumberFormatter to return the formatted string without blanc spaces in it ? (1.000,00€)

like image 975
Oysio Avatar asked Apr 13 '10 19:04

Oysio


1 Answers

It's an old question but I just ran into the same problem. The space character which NSNumberFormatter is using is not the standard space you provided in your replace method.

It is some kind of special character. You can retrieve it by using NSLog then copy that mysterious space from your debug window and paste it into your replace method

formattedPrice = [formattedPrice stringByReplacingOccurrencesOfString:@" " withString:@""];

Copy and paste my line should also do (don't know what the browser does with it though...)

like image 158
JohnPayne Avatar answered Sep 19 '22 00:09

JohnPayne