Saturday, July 30, 2005

Formatting Numbers in Monad

Monad is pretty clever when it comes to displaying and formatting variables. To display a variable you just specify the variable name - either on it's own or with some maths such as:

[C:\]: #display normal number
[C:\]: $number = 123
[C:\]: $negativenumber = -23.23
[C:\]: $number
[C:\]: $negativenumber
[C:\]: #display with arithmetic on the line
[C:\]: $number-23.23
[C:\]: #display formatted string
[C:\]: "String with number ($number) inside"
String with number (-23.23) inside
[C:\]: $number = 234
[C:\]: "String with arithmetic (number+1) ($($number+1)) inside"
String with arithmetic number+1 (235) inside

Well, that's all fine and well, but what if you want more control over your formatting? What if you want neat columns of numbers? I did some searching and found a blog posting from the BCL team which described formatting numbers in .NET, using C#. It was a pretty easy matter to convert the basic code presented in the blog entry into to a Monad script that demonstrates how to format numbers into strings. The script is Format-Number.Msh on my Monad sample scripts page.

As the script shows, there are a couple of ways to get nicely formatted numbers in strings. The main tools you use to get formatted numbers is the tostring() method (which every .NET object implements), the format types you can specify to tostring(), and then using the "-F" parameter to format these numbers into a display string. For example:

[C:\]: "{0,5} times 2 equals {1,10}" -f 10, $(10*2)
10 times 2 equals 20

Armed with this, it's just a matter of adjusting the format strings and the lengths of each field to get output just the way you want it.

No comments: