[Newbies] Number formatting printf/sprintf for Squeak?

Michael van der Gulik mikevdg at gmail.com
Mon Feb 16 22:44:34 UTC 2009

On Tue, Feb 17, 2009 at 10:44 AM, Sorensen <sorens at surfy.net> wrote:

> Is there a printf/sprintf-like package for formatting text  for Squeak?
> If not, how do Squeakers go about formatting currency amounts or left
> justifying text within a field?

My initial reaction was "that's obvious; there are methods in the String
class", but when I looked I realised that this isn't actually as trivial as

For printf-like functionality, class String has a "formatting" category with
undocumented methods. The excellent "Squeak by Example" book has some
examples (http://scg.unibe.ch/SBE/SBE.pdf, page 208) but the functionality
is very limited compared with printf.

See also SequenceableCollection>>copyReplaceAll:with:

For formatting currency, I notice there's a Locale class with
Locale>>primCurrencySymbol, but I can't find any more advanced methods for
actually formatting a currency, and I can't find any currency classes for
any Smalltalk dialect on Google (!), apart from an LcMonetary class for GNU

For left-justifying text, I'm a bit surprised that you'd want to do this.
Typically, you'd make the text left or right justified in whatever GUI
element that value ends up in, rather than padding it with spaces.

Anyway; some code examples for actually doing the above:

Formatting a currency (specifically in my Locale) with two decimal places:

" I assume that you're using ScaledDecimals for the currency; you generally
shouldn't use Floats for currency. "
c := ScaledDecimal newFromNumber: 123.45 scale: 2.
" It's good practise to use a stream for formatting strings manually "
stream := WriteStream on: (String new: 30).
c >= 0 ifTrue: [ stream nextPut: $- ].
stream nextPutAll: Locale current primCurrencySymbol. " Generally, prim
methods should be private... "
c printOn: stream. " Bug: also prints out 's2'. "
result := stream contents.

I would also add a new method to ScaledDecimal to print out its value
without appending an 's2'. In fact, I'd probably make a subclass of Number
or ScaledDecimal called "Currency" and release it as a reusable package.

Left-justifying text with padding:

padding := String new: 40.
padding replaceAll: (Character value: 0) with: $ .

s := 'format me'.
result := padding copy replaceFrom: 1 to: s size with: s.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.squeakfoundation.org/pipermail/beginners/attachments/20090217/a333a9d0/attachment.htm

More information about the Beginners mailing list