stringWithFormat_

Is there something I’m missing here:

current application's NSString's stringWithFormat_("%.3f", 2.456789)

The result I get is (NSString) "0.000".
No matter if the given value is of class real, NSDouble, NSFloat or NSString.
(I get the same result with localizedStringWithFormat_)


MacOS 12.7.5 (21H1222) French localization
Script Debugger 8.0.7 (8A77)

Hi @ionah.

I hadn’t known that stringWithFormat_ was supposed to be able to format numbers. I get the same results as you. Maybe you could use NSNumberFormatter instead. A number formatter can be configured in several different ways, including for your simple example above:

use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"

set formatter to current application's NSNumberFormatter's new()
formatter's setMaximumFractionDigits:3
-- formatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"fr")
formatter's stringFromNumber:2.456789 -->"2.457"

Jonas. Does Shane’s response (here) address this issue:

The problem is inherent in the way the scripting bridge works. When you pass an integer or a real to a method, the bridge automatically converts it to an NSNumber object – they aren’t seen as integers or floats by Cocoa, so you can’t use the various tokens like %d and %f.

Everything from AppleScript gets turned into an object of some kind, so the only token you can use is %@. And that doesn’t give you a lot of options.

1 Like

Thanks guys, I had completely forgotten about that.