How to create a custom locale with a custom value of NSDecimalSeparator?

I'm having problems with

+ (NSDecimalNumber *)decimalNumberWithString:(NSString *)numericString locale:(NSDictionary *)locale 

Since I want to provide very high precision values ​​programmatically so that I don't initially have floating point errors, apple gives me the only way to rely on an unstable locale.

Thus, the documentation speaks of a rather encrypted form:

Parameters: ... place of action A dictionary that defines the locale (in particular, NSDecimalSeparator) to use in interpret the number in a number line.

Discussion The locale parameter determines whether the NSDecimalSeparator is a period (as used, for example, in the USA) or a comma (used, for example, in France).

Well, after searching for NSDecimalSeparator, nothing was found in the documents. A network search found that this item is "out of date." So now I am doing something dangerous:

 NSLocale *usLoc = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; NSDecimalNumber *num = [NSDecimalNumber decimalNumberWithString:str locale:usLoc]; 

So, I wonder: if they really need this warlike locale for something important (I add lines programmatically, without user input), could I somehow create my own language? This parameter wants an NSDictionary, so the idea is:

Can I create an NSMutableDictionary from this language dictionary that appears for -initWithLocaleIdentifier: @ "en_US" and then just edit this%? & §! NSDecimalSeparator field?

And one more thing that raises my headaches: why does the parameter ask for the NSDictionary, where do I need to pass the NSLocale object? Or is my code incorrect? (not tested since my application is currently completely confused ;-))

+4
source share
1 answer

There is no way to add / change values ​​in an instance of NSLocale ; you can get the logical language for the user ( currentLocale and autoupdatingCurrentLocale ), the language standard of the system without any changes made by the user to their system preferences ( systemLocale ), or any other named language that the system knows about ( initWithLocaleIdentifier ).

NSLocale responds to an objectForKey: message, which is the same message that NSDictionary uses; therefore, you can use NSLocale , although the method calls NSDictionary . Since NSDecimalNumber is likely to look at only one value, NSDecimalSeparator , I have the feeling that you can go away with creating an NSDictionary object with this key and pass it as the locale parameter, but this may break in the future, since NSDecimalNumber expects a full-blown instance of NSLocale and may be modified to verify other keys.

You create these lines programmatically, right? This way you can control which decimal separator you use. My recommendation would be to use . and get the en_US locale:

 NSLocale *us = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 

A decimal separator will be required . everytime.

+5
source

All Articles