I have decimal numbers stored in my database as decimal. And I display them according to the user's locale:
- (NSString *) getLocalizedCurrencyStringWithDigits
{
NSNumberFormatter *numberFormatter =[[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setMinimumFractionDigits:2];
[numberFormatter setMaximumFractionDigits:2];
NSString *numberString = [numberFormatter stringFromNumber:self];
return numberString;
}
And I display these strings in textfields, that are editable. So if a user starts to edit the field, I want to remove the thousand separator. Otherwise (in my country) I enter 1'000.55 and it then doesn't recognize the "'" and saves just a 1. Here is my function to parse the textfields and in the view controllers this exact return value will be saved to the database:
+ (NSDecimalNumber *) getUnLocalizedDecimalNumberWithString:(NSString *)currencyString
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setMinimumFractionDigits:2];
[numberFormatter setMaximumFractionDigits:2];
BOOL isDecimal = [numberFormatter numberFromString:currencyString] != nil;
if(isDecimal){
return [NSDecimalNumber decimalNumberWithString:currencyString locale:[NSLocale currentLocale]];
} else {
return [NSDecimalNumber zero];
}
However I don't get it to work...actually it would be best if numbers with"'" and without would be saved correctly but I don't get it to work :/
EDIT (my solution): Got it working like this:
- (NSString *) getLocalizedCurrencyStringWithDigits:(int)digits
{
NSNumberFormatter *numberFormatter =[[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setMinimumFractionDigits:digits];
[numberFormatter setMaximumFractionDigits:digits];
NSString *numberString = [numberFormatter stringFromNumber:self];
return numberString;
}
+ (NSDecimalNumber *) getUnLocalizedDecimalNumberWithString:(NSString *)currencyString
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setMinimumFractionDigits:2];
[numberFormatter setMaximumFractionDigits:2];
NSNumber *formatedCurrency = [numberFormatter numberFromString:currencyString];
BOOL isDecimal = formatedCurrency != nil;
if(isDecimal){
return [NSDecimalNumber decimalNumberWithDecimal:[formatedCurrency decimalValue]];
} else {
return [NSDecimalNumber zero];
}
}
+(NSDecimalNumber *) getUnLocalizedDecimalNumberWithString:(NSString *)currencyString
interprets now every string correctly. 1'000 and 1000 and 1000.00 are all 1000 now :-)