Search code examples
ioscurrencynsnumberformatter

How to convert a currency string to number


I have the following string:

R$1.234.567,89

I need it to look like: 1.234.567.89

How can i do this?

This is what i tried:

NSString* cleanedString = [myString stringByReplacingOccurrencesOfString:@"." withString:@""];
cleanedString = [[cleanedString stringByReplacingOccurrencesOfString:@"," withString:@"."]
                                     stringByTrimmingCharactersInSet: [NSCharacterSet symbolCharacterSet]];

It works, but I think there must be a better way. Suggestions?


Solution

  • If your number always after $, but you got more characters before it, you can make it like this:

    NSString* test = @"R$1.234.567,89";
    NSString* test2 = @"TESTERR$1.234.567,89";
    NSString* test3 = @"HEllo123344R$1.234.567,89";
    
    
    NSLog(@"%@",[self makeCleanedText:test]);
    NSLog(@"%@",[self makeCleanedText:test2]);
    NSLog(@"%@",[self makeCleanedText:test3]);
    

    method is:

    - (NSString*) makeCleanedText:(NSString*) text{
    
        int indexFrom = 0;
    
        for (NSInteger charIdx=0; charIdx<[text length]; charIdx++)
            if ( '$' == [text characterAtIndex:charIdx])
                indexFrom = charIdx + 1;
    
        text = [text stringByReplacingOccurrencesOfString:@"," withString:@"."];
        return [text substringFromIndex:indexFrom];
    }
    

    result is:

    2013-10-20 22:35:39.726 test[40546:60b] 1.234.567.89
    2013-10-20 22:35:39.728 test[40546:60b] 1.234.567.89
    2013-10-20 22:35:39.731 test[40546:60b] 1.234.567.89