use framework "Foundation"
use framework "AppKit"
use scripting additions
my formatNumber:6.54321E+4 byPattern:"#,##0.00" --> 65,432.10
my formatNumber:6.54321E+4 byPattern:"#,###.##" --> 65,432.1
my formatNumber:"65432,1044" byPattern:"#,##0.00" --> 65,432.10
on formatNumber:theNumber byPattern:thePattern
if class of theNumber = text then set theNumber to theNumber as real
set theFormatter to current application's NSNumberFormatter's new()
theFormatter's setFormat:thePattern
theFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"en_US")
set theResult to theFormatter's stringFromNumber:theNumber
return theResult
end formatNumber:byPattern:
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
use script "Number" version "1.0"
set dowClosing to 3.456789E+4
try
set dowClosingText to format number dowClosing ¬
using "#,###.##"
on error errText number errNum
set errorString to "Error Message: " & errText & return & return & "Error number: " & errNum as text
set buttonList to {¬
("Copy"), ¬
("Okay") ¬
}
set errDialogReply to display dialog errorString ¬
with title ("Error: " & errNum) ¬
default answer (errNum as text) & ": " & errorString ¬
buttons buttonList
if button returned of errDialogReply contains "Copy" then
set the clipboard to errorString
end if
end try
→ Script Debugger 8.0.4 (8A52)
→ Mac OS 11.6.5 (20G527)
Works here (12.4). Have you changed your Script Libraries folder? Check the TypeSupport library is present. If you run it without the try block, what’s the error?
It seems to ignore the format’s dictate that it returns two decimal places, which AppleScript wouldn’t allow if the second decimal place was a zero, but as a string, one would expect the trailing zero to be present.
Yes. TypeSupport is used by all libraries to ensure that parameters are the correct type, and provide descriptive error messages if not.
(While AS handler parameters can be directly annotated with types, AS doesn’t tell you which handler or parameter failed which is next to useless; hence the extra library to do the job right.)