What locale argument to pass to NSDecimalNumber +decimalNumberWithString:locale: so it always works with NSString's using the dot (.) decimal mark?

烈酒焚心 提交于 2019-12-06 01:26:59

问题


I have an NSString which I want to convert into an NSDecimalNumber. The string is received from a server and is always formatted using the en_US locale like XXX.YYY and not like XXX,YYY. I want to create an NSDecimalNumber which accepts XXX.YYY regardless of the locale the user. The number is never displayed to the user, it's used to do internal math.

Normally you'd do something like this:

NSDecimalNumber *n = [NSDecimalNumber decimalNumberWithString:@"1.234"];

However, if the user is running the fr_FR locale of Mac OS X, that will break. en_US will interpret it as one point two three four, where-as fr_FR will interpret it as one-thousand two-hundred thirty-four, both very different numbers.

The obvious solution is to use +decimalNumberWithString:locale:. But I'm not sure what to pass as an argument to the locale: parameter which will work on all international versions of Mac OS X. My best guess is to do this:

NSLocale        *l = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];
NSDecimalNumber *n = [NSDecimalNumber decimalNumberWithString:@"1.234" locale:l];

Is that the best way to do this, and is it safe? Will the @"en_US" local identifier be available on all international versions of Mac OS X, or might it return a nil NSLocale in some cases?


UPDATE 1: This appears to work well, and is more explicit:

NSDictionary    *l = [NSDictionary dictionaryWithObject:@"." forKey:NSLocaleDecimalSeparator];
NSDecimalNumber *n = [NSDecimalNumber decimalNumberWithString:@"1.234" locale:l];

NSLocaleDecimalSeparator is a constant defined for NSLocale, which responds to -objectWithKey:, just like NSDictionary. You can feed it any decimal mark separator you want, like @",".

I think this is likely the best answer to the question, unless anyone else has a better idea?


回答1:


This appears to work well, and is more explicit:

NSDictionary    *l = [NSDictionary dictionaryWithObject:@"." forKey:NSLocaleDecimalSeparator];
NSDecimalNumber *n = [NSDecimalNumber decimalNumberWithString:@"1.234" locale:l];

NSLocaleDecimalSeparator is a constant defined for NSLocale, which responds to -objectWithKey:, just like NSDictionary. You can feed it any decimal mark separator you want, like @",".

I think this is likely the best answer to the question, unless anyone else has a better idea?



来源:https://stackoverflow.com/questions/7879361/what-locale-argument-to-pass-to-nsdecimalnumber-decimalnumberwithstringlocale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!