Monthly Archive

Categories

Scripting Games comments X: String Substitution 2

Noticed something like this while judging scripts last week

PS> $comp = Get-WmiObject -Class Win32_ComputerSystem
PS> $mem =  ($comp.TotalPhysicalMemory / 1GB).ToString() + "GB"
PS> $mem
2.74846267700195GB

The value was been divided by 1GB – good -  and then being converted to a string so could add a suffix.

Its easier to do this

PS> $mem = "$($comp.TotalPhysicalMemory / 1GB)GB"
PS> $mem
2.74846267700195GB

Unless of course you want to format the string a bit further

PS> $mem = "{0:F2}GB" -f $($comp.TotalPhysicalMemory/1gb)
PS> $mem
2.75GB

We can use the .NET formatting to format the number of decimal places or going back to our original

PS> $mem =  ($comp.TotalPhysicalMemory / 1GB).ToString("F2") + "GB"
PS> $mem
2.75GB

Lots of ways to format numbers into strings – pick what’s easiest for your particular job

Leave a Reply