views:

122

answers:

1

In Brad's CorePlot I've seen this snippet, which eliminated the need for some coffee. I'm totally awake now:

NSDecimal result;
NSScanner *theScanner = [[NSScanner alloc] initWithString:stringRepresentation];
[theScanner scanDecimal:&result];

And Apple says:

A scanner’s locale affects the way it interprets values from the string. In particular, a scanner uses the locale’s decimal separator to distinguish the integer and fractional parts of floating-point representations. A new scanner’s locale is by default nil, which causes it to use non-localized values.

So: If I create a NSScanner instance and don't provide a locale, it will expect the decimal value represented by the string just like if I typed it in plain source code in?

i.E. @"-59933845504572.944882211" or @"123.456789" or @"145.002e33" or @"145.002e-33"? Would that be correct?

+1  A: 

NSScanner will extract a numerical value from a string in the same way as if you had initialized an NSDecimalNumber with that string. You can follow NSDecimalNumber's rules as to what it can parse.

According to the scanners section of Apple's "String Programming Guide for Cocoa", the localization will be based on the user's locale. You can change this using setLocale: if you would like to manually supply a decimal separator.

We used the NSScanner to initialize the NSDecimal from a string because it was significantly faster than using NSDecimalNumber with code like the following:

NSDecimalNumber *newNumber = [[NSDecimalNumber alloc] initWithString:@"1.0" locale:[NSLocale currentLocale]];
newDecimal = [newNumber decimalValue];
[newNumber release];

NSScanner did about 582000 conversions per second, where NSDecimalNumber only did 307000 on my Mac.

Brad Larson
Thanks. One thing though. The documentation says: "A new scanner’s locale is by default nil, which causes it to use non-localized values." Doesn't that mean, that a scanner will work for hard-coded strings regardless of the user's locale? Or am I really safer with specifying the US locale, for example?
HelloMoon
I don't know. You could test this out by running an application in the iPhone Simulator (or Mac) under both U.S. and German locales and see if it handles the change in decimal separator without a hitch.
Brad Larson
Good idea. Learned a new word "hitch". Thanks for that, too ;-)
HelloMoon