Iphone – How would an NSScanner expect a string for scanning an NSDecimal

cocoa-touchiphoneuikit

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?

Best Answer

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.