Using System.Math

While PowerShell itself comes with reasonably basic mathematical operators, the .NET System.Math class has a far wider variety.

The Round static method can be used to round up to a fixed number of decimal places. In the following example, the value is rounded to two decimal places:

[Math]::Round(2.123456789, 2) 

By default, the Round method in .NET performs what's known as bankers rounding. It will always prefer to round to an even number. For example, 1.5 will round to 2, and 2.5 will round to 2.

This behavior can be changed using the MidpointRounding enumeration, as shown here:

[Math]::Round(2.225, 2)                                     # Results in 2.22
[Math]::Round(2.225, 2, [MidpointRounding]::AwayFromZero) # Results in 2.23

The Ceiling and Floor methods are used when performing whole-number rounding:

[Math]::Ceiling(2.1234)    # Returns 3 
[Math]::Floor(2.9876)      # Returns 2 

The Abs converts a positive or negative integer into a positive integer (and multiplies by -1 if the value is negative):

[Math]::Abs(-45748) 

Numbers may be raised to a power using the following syntax:

[Math]::Pow(2, 8) # Returns 256 (28) 

A square root can be calculated as follows:

[Math]::Sqrt(9)    # Returns 3 

The System.Math class also contains static properties for mathematical constants:

[Math]::pi    # π, 3.14159265358979 
[Math]::e     # e, 2.71828182845905 

Methods are also available to work with log, tan, sin, cos, and so on.

For a deeper dive into math in PowerShell, Tim Curwick's blog uncovers more detail. The article is available at https://www.madwithpowershell.com/2013/10/math-in-powershell.html.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.61.16