Tuesday, February 18, 2014

Powershell oddity with formatting strings

I executed this:
"{0:C}" -f 120*500000

This is what I thought this was equivalent to:
String.Format(“{0:C}”, 120*500000)

Here’s what it really did:
Printed $120 500000 times. I think that means it did this:

new string(String.Format("{0:C}", “120”), 500000)
which is sorta equivalent to this:
For(int i = 0; I < 500000; i++)
{
String.Format("{0:C}", “120”);
}

I know the multiply operator is overloaded for strings, so
"120"*5 would be equivalent to new string("120", 5). 

So this must be order of operations weirdness and implied parentheses, like
"{0:C}" -f 120*500000 == ("{0:C}" -f 120)*500000

It would make much more sense if it implicitly grouped everything AFTER the -f flag together into a subexpression, in other words:
"{0:C}" -f 120*500000 == "{0:C}" -f $(120*500000)

What i had to do to get the desired behavior was this:
 "{0:C}" -f $(120*500000)

Doesn't make sense to me that i would have to wrap that in a subexpression. Should be implicit.

No comments:

Post a Comment

There was an error in this gadget