Monday, July 25, 2011

PowerShell strings, ints and comparisons

I hit this doing a little bit of playing around over the weekend, porting some old BASIC progams into PowerShell.

Most of the time treating strings of digits as numbers "just works":

>$line = "5, 22.5"
>$bits = $line.split(",")
>$bits
5
 22.5
>$ratio = $bits[1]/$bits[0]
>$ratio
4.5
>write-host ($bits[0] -eq 5)
True

but at times it all goes horribly wrong

>write-host ($bits[0] -gt 30)
True
>write-host ($bits[0] -gt 60)
False
>write-host ($bits[0] -gt 50)
False
>write-host ($bits[0] -gt 49)
True
>write-host ($bits[0] -eq 50)
False

with the ASCII value of '5' being 53, we see that these comparisons are being done lexically.

What is needed in these circumstances is an explicit coercion some place down the line; like:

>write-host ([int]$bits[0] -gt 45)
False

Post a Comment