On 21 Jan 2014, at 10:25 am, Deivy Petrescu <email@hidden> wrote:
I am getting very upset with you Shane! You are making it very compelling for us all to go into ASOC.
What is your goal??? Progress???
Perish the thought. But for completeness, here are some similar handlers for numbers. One of the pains of AppleScript is the way it reverts to scientific notation with sizeable numbers, so here's a simple handler to avoid that:
use framework "Foundation"
on formatNumber:theNumber set theFormatter to current application's NSNumberFormatter's new() theFormatter's setNumberStyle:(current application's NSNumberFormatterDecimalStyle) set theResult to theFormatter's stringFromNumber:theNumber return theResult as text end formatNumber:
Called by:
use theLib : script "<lib name>"
set theNumber to 1.234567890123E+12 set theResult to theLib's formatNumber:theNumber --> "1,234,567,890,123"
You can also use format strings similar to dates, and again you might want them localized or not. Rather than naming a locale, it's probably easier to use a boolean flag:
on formatNumber:theNumber usingFormat:formatString localized:localizeFlag set theFormatter to current application's NSNumberFormatter's new() theFormatter's setFormat:formatString theFormatter's setLocalizesFormat:localizeFlag set theResult to theFormatter's stringFromNumber:theNumber return theResult as text end formatNumber:usingFormat:localized:
on formatNumber:theNumber usingFormat:formatString return my formatNumber:theNumber usingFormat:formatString localized:true end formatNumber:usingFormat:
So this will return the same result regardless of locale:
theLib's formatNumber:1.2345678E+4 usingFormat:"#,###.00;0.00;(#,##0.00)" localized:false --> "12,345.68"
And leaving off the localized: parameter (or setting it to true) will use your Mac's locale to decide what to use as thousands and decimal separators.
Finally, you may sometimes need numbers spelled out:
on textFromNumber:theNumber set theFormatter to current application's NSNumberFormatter's new() theFormatter's setNumberStyle:(current application's NSNumberFormatterSpellOutStyle) set theResult to theFormatter's stringFromNumber:theNumber return theResult as text end textFromNumber:
Called like:
theLib's textFromNumber:1.2345678E+4 --> "twelve thousand three hundred forty-five point six seven eight"
Two tips:
* It's a good idea to keep lots of this sort of general stuff in a single library, adding as you go. Then you only need a single "use" statement, and you don't have to try remembering lib names (I use "General lib".)
* The "use framework..." statement(s) only need to appear once in a library, preferably at the start.
|