Hi All,
I’ve run into the following issue a few times and in the past I’ve put something kludgy together, but I thought I’d finally see if there are any slick ways to handle it. Lets say I have the following script.
set a to "1.5"
set b to a * 10
In the US, b = 15.0. In countries like Spain, b = 150. In France you get an error - “Can’t make “1.5” into type number.” This is all due to how various countries handle decimals. I need the answer to be the string “15.0” regardless of the regional localization of the computer the application is run on. Has anyone run into this issue and have a solution. I was hoping that now with ASOC opening applescript up the the world of obj-c that I would find something there, but I haven’t had any luck.
Thanks in advance for any responses.
Hi,
you are trying to do math with a string. AppleScript coerces a string to number implicitly if possible
by considering the current number format settings.
In pure AppleScript you could identify the local decimal separator and replace the dot with a comma
in a comma based decimal system before coercing the string to number.
In ObjC / AppleScriptObjC use NSNumberFormatter
property NSNumberFormatter : class "NSNumberFormatter"
property NSLocale : class "NSLocale"
set a to "1.5"
set numberFormatter to NSNumberFormatter's alloc()'s init()
set usLocale to NSLocale's alloc()'s initWithLocaleIdentifier_("en_US")
numberFormatter's setNumberStyle_(current application's NSNumberFormatterDecimalStyle)
numberFormatter's setLocale_(usLocale)
set theNumber to numberFormatter's numberFromString_(a) as real
log theNumber * 10 --> 15.0
usLocale's release()
numberFormatter's release()
That’s what I was looking for. Thanks!
I take it that the release()'s are for memory management. Is that required?
In a Garbage Collection environment no.
Personally I’m always using memory management, because iOS doesn’t provide GC anyway
After playing around with this some more I’ve noticed something unusual. There is some sort of round off error going on. “1.5” is converted to 1.5, but "1.325 yields 1.325000047683716, and “1.9” becomes 1.899999976158142. Do I have to manually round? That seems odd.
the problem is the AppleScript as real coercion, which is pretty inaccurate.
Better use the ObjC coercion
.
set theNumber to numberFormatter's numberFromString_(a)
log theNumber's doubleValue() * 10