Reputation: 387
I have these number formats:
100000,459
100000459
100.000
100.000,59
100.000.000,39
The number changes as the user input values to it. And for every value added, I need to re-format the number with NSNumberFormatter. The problem is that this number already has . and , and the formatter does not seem to handle these correctly. It comes out like this:
100 000,00
100 000 459,00
100,00
100,00
100,00
E.g. I want 100000,459 to become 100 000,459.
The code I use now:
NSNumber *amount = [NSNumber numberWithInt:[string intValue]];
NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"nb_NO"];
[currencyFormatter setLocale:locale];
NSString *commaString = [currencyFormatter stringForObjectValue:amount];
How can I format already formatted numbers?
Upvotes: 0
Views: 794
Reputation: 10090
NSNumberFormatter
formats a number to a string representation and it needs the correct representation of the number to be able to format it as expected. By the look of your code sample you are providing the formatter with an integer value and that is why you are getting the output you are getting. With string = @"100000,459"
[string intValue]
gives you 100000
. Which is why the output from the formatter is 100 000,00
.
What you need to do is to first get the string into a double representation. That can be achieved by using NSScanner
. You just have to make sure that you scan the numbers in the correct locale so the thousand separators are detected properly. Your first string can be converted to a double by:
NSScanner *scanner = [NSScanner scannerWithString:@"100000,459"];
[scanner setLocale:locale];
double val;
[scanner scanDouble:&val];
NSNumber *amount = [NSNumber numberWithDouble:val];
How to properly handle the thousand separators I don't know.
Upvotes: 0
Reputation: 387
I've looked at that specific reference. It differs from my problem because in my case I may already have decimals when formatting.
Upvotes: 0
Reputation: 150705
In the last line you are trying to format a string rather than a number. Try this:
NSString *commaString = [currencyFormatter stringFromNumber:amount];
Here is a good reference.
Upvotes: 1