Problem
You want to use PowerShell to calculate simple mathematical results.
Solution
Use PowerShell’s arithmetic operators:
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus
+=, -=, *=, /=, and %= Assignment variations of the above ( ) Precedence/Order of operations
Discussion
One difficulty in many programming languages comes from the way that they handle data in variables. For example, this C# snippet stores the value of “1” in the result variable, when the user probably wanted the result to hold the floating point value of 1.5:
double result = 0; result = 3/2;
This is because C# (along with many other languages) determines the result of the division from the type of data being used in the division. In the example above, it decides that you want the answer to be an integer since you used two integers in the division.
PowerShell, on the other hand, avoids this problem. Even if you use two integers in a division, PowerShell returns the result as a floating point number if required. This is called widening.
PS >$result = 0 PS >$result = 3/2 PS >$result
1.5
One exception to this automatic widening is when you explicitly tell PowerShell the type of result you want. For example, you might use an integer cast ([int]) to say that you want the result to be an integer after all:
PS >$result = [int] (3/2) PS >$result 2
Many programming languages drop the portion after the decimal point when they convert them from floating point numbers to integers. This is called truncation. PowerShell, on the other hand, uses banker’s rounding for this conversion. It converts floating point numbers to their nearest integer, rounding to the nearest even number in case of a tie.
Several programming techniques use truncation, though, so it is still important that a scripting language somehow support it. PowerShell does not have a builtin operator that performs a truncationstyle division, but it does support it through the [Math]:: Truncate() method in the .NET Framework:
PS >$result = 3/2 PS >[Math]::Truncate($result) 1
If that syntax seems burdensome, the following example defines a trunc function that truncates its input:
PS >function trunc($number) { [Math]::Truncate($number) } PS >$result = 3/2 PS >trunc $result 1