PowerShell for Windows Admins

Jan 1 2011   5:19AM GMT

Truncating numbers



Posted by: Richard Siddaway
PowerShell v2

This is something I fell foul of recently. I had a calculation that produced a non integer answer e.g.  2.1

I needed to get the integer part of the number.  Without really thinking about it I did this

PS> [int]2.1
2

I was then a bit surprised when I didn’t always get the right answer.  Still not thinking I was scratching my head until I realised that using [int] rounds to the nearest integer.

PS> for ($i=2.1; $i -le 3.0; $i+=0.1){"$i  $([int]$i)"}
2.1  2
2.2  2
2.3  2
2.4  2
2.5  3
2.6  3
2.7  3
2.8  3
2.9  3

This is no good because I need to round down.

The .NET Math class has a Truncate method that works however.

PS> for ($i=2.1; $i -le 3.0; $i+=0.1){"$i  $([math]::Truncate($i))"}
2.1  2
2.2  2
2.3  2
2.4  2
2.5  2
2.6  2
2.7  2
2.8  2
2.9  2

And the moral of the story is that you need to think about what you are doing and not assume that things work the way you think they do

Comment on this Post

Leave a comment: