2 + 2 equals "Monday Evening"

2 + 2 equals "Monday Evening"

  • Comments 3

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

Leave a Comment
  • Please add 4 and 7 and type the answer here:
  • Post
  • But you said in the previous post that the data type of the result is the data type of the first operand. So how does the int get converted to a double?

  • I had no idea you were so musical.

    My guess is that PowerShell makes a special exception for division.

  • I'm just guessing, but is it possibly when the types are incompatible that the first operand is used in this way?

    Internally, the + operator works as an overloaded function.  When you use + with strings, it concatenates.  When you use it with numeric types (floats, doubles and integers).  Because .NET has a + operator that can add floats to integers, it uses that, and returns whatever that returns.

Page 1 of 1 (3 items)