Search code examples
iosobjective-cnsnumberformatter

NSNumberFormatter removing spaces before currency


I am using NSNumberFormatter to format my numbers to strings. I have a device with Hebrew (israel) region format (settings->General->International->Region Format). When I try to format the number 100 for instance I get 100 $. My goal is to remove the space before the currency sign and get just 100$


Solution

  • I ended up changing positiveSuffix and negativeSuffix properties by removing the spaces from them

    because my NSNumberFormatter is static in my application I set them to nil at the end of each use

    static NSNumberFormatter *currencyFormatter;
    if (!currencyFormatter) {
         currencyFormatter = [[NSNumberFormatter alloc] init];
         [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
         [currencyFormatter setNegativeFormat:@""];
    }
    
    // remove spaces at the suffix
    currencyFormatter.positiveSuffix = [currencyFormatter.positiveSuffix stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    currencyFormatter.negativeSuffix = [currencyFormatter.negativeSuffix stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    
    // get the return number
    NSString* retNum = [currencyFormatter stringFromNumber:val];
    
    // this code is for the next time using currencyFormatter
    currencyFormatter.positiveSuffix = nil;
    currencyFormatter.negativeSuffix = nil;
    
    return retNum;