January 9th, 2007

2 + 2 equals "Monday Evening"

PowerShell Team
PowerShell Team

I wanted to follow up on Jeffrey’s post and one of the comments.  It has to do with this example:

PS> [int]1/2
0.5

The reason that we get a double rather than an int is because of precedence.  The conversion has a higher precedence than the division operation, so what

[int]1/2

really means is:

“Convert 1 to an integer and then divide by 2”, which will result in a double (0.5).  If we really want our results to be an integer, we should do the following:

[int](1/2)

which first does the division and then converts to an integer.  Viola, we get what we want!

PS> [int](1/2)
0

Jim Truher [MSFT]
Windows PowerShell Program Manager
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Category
PowerShell

Author

PowerShell Team
PowerShell Team

PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes.

0 comments

Discussion are closed.