PowerShell for Windows Admins

Jan 1 2011   5:19AM GMT

Truncating numbers

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: