Jules
Jules

Reputation: 7774

Obj-C, currency value to workable number, issue

I've been building a currency removal function which will work across the globe. However a bug has come to light and unsure why.

+(double)removeFormatPrice:(NSString *)strPrice {

    NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] 
        autorelease];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber* number = [currencyFormatter numberFromString:strPrice];

    NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] 
        autorelease];
    NSMutableString *mstring = [NSMutableString stringWithString:strPrice];
    NSRange wholeShebang = NSMakeRange(0, [mstring length]);

    [mstring replaceOccurrencesOfString: [formatter decimalSeparator]
                             withString: @"."
                                options: 0
                                  range: wholeShebang];

    double newPrice = [mstring doubleValue];
    if (number == nil) {

        return newPrice;
    } else {
        return [number doubleValue];
    }
}

If I pass in 1,000.00 then it replaces the dot (period / full stop) it should just do that, but it also replaces the comma. Newprice comes out as 1. Heres my full debug... enter image description here

Upvotes: 0

Views: 139

Answers (2)

Costique
Costique

Reputation: 23722

What's happening is that -[NSString doubleValue] fails to parse the string "1,00000", stopping at the comma, and returns "1". Instead, you should just format number according to your needs. Configure the formatter with the proper format you need and use it to get the final string. Don't replace any characters manually when you can rely on the framework.

EDIT: Complete code example

NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSNumber* number = [currencyFormatter numberFromString:strPrice];

NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setPositiveFormat: @"#.00"];
NSLog(@"%@ %@", number, [formatter stringFromNumber: number]);

On my machine with the current locale I get:

1000 1000,00

Upvotes: 0

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

Use this

[mstring replaceOccurrencesOfString: [formatter groupingSeparator]
                             withString: @""
                                options: 0
                                  range: wholeShebang];

Upvotes: 1

Related Questions