Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.
If you own the book already, login here to get free, online, searchable access to the entire book's content.
If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".
You want to use PowerShell to calculate simple mathematical results.
Use PowerShell’s arithmetic operators:
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
% |
Modulus |
+=, -=, *=, /=, and %= |
Assignment variations of the previously listed operators |
() |
Precedence/order of operations |
For a detailed description of these mathematical operators, see “Simple Operators”.
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 previous example, it decides that you want the answer to be an integer because 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’s still important that a scripting language somehow support it. PowerShell doesn’t have a built-in operator that performs truncation-style 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
“Simple Operators”