Question

I have a screen where the user can enter some information. It shows a decimalPad. According to the user locale, I know the decimalPadwill show commaor period, or even something else.

Therefore, my database will contain NSStrings stored from the users, although, some of them will have comma, like 5,4, or period, as in 5.4. The problem is that I need to do some math with these values, and I can't find a pattern to convert them.

Lets say the NSStringhas a comma, as in 5,4. I can easily convert that to a floatusing:

NSNumberFormatter *commas = [NSNumberFormatter new];
commas.numberStyle = NSNumberFormatterDecimalStyle;
NSLocale *commaLocale = [[NSLocale alloc] initWithLocaleIdentifier: @"br_PT"];
commas.locale = commaLocale;

NSString *string = @"5,4";
float testFloat = [[commas numberFromString:string] floatValue];

I correctly get the result 5.4, and can go on with my math calculations. But for instance, if the number was saved by an US user, the NSString would be 5.4, and I wouldn't get the right result using this code. Even if I get user current locale, it doesn't help me, since the user will get values stored all around.

Anyway, I'm a little confused with this. How could I simply create a pattern to deal with this?

I don't want to work with the string, as in stringByReplacingOccurences..., anyway, at least if I can avoid that.

Was it helpful?

Solution

If you want to use the value as a number, you should store the value as a number in your database. NSNumber is a perfect object for that and with your method you can get correct value. When you show the value again to the user you should convert the NSNumber again with NSNumberFormatter. Everything else will be a workaround and have negative impact. Even with stringByReplacingOccurences... you have the risk that somebody uses thousand-dots or commas...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top