Archive for 20th June 2012

Locale friendly numeric entries

If you are ever planning to have someone from a country other than the U.S. use your iOS application, then I would go through right now and check for all the floatValue and doubleValue methods of NSString, and get rid of them if the NSString is coming from data that the user can enter. Needless to say, those users in Europe who use a comma for the decimal separator and a period for the thousands separator will notice some hilarities when using your app.

I put together a quick method in my NSString categories code (notice that it uses self as the source string) that I am using to avoid this very issue. Here is what it looks like:

- (double)localeSafeDecimalValue
{
    NSNumberFormatter *decimalStyle = [[NSNumberFormatter alloc] init];
    [decimalStyle setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *n = [decimalStyle numberFromString:self];
    [decimalStyle release];
    return [n doubleValue];
}

This will work as long as the user is entering numbers in the format that their International Settings are set to on their iOS device.

BTW, happy birthday to Michael Anthony, bass player and backup singer of Van Halen and Chickenfoot fame.