How-to: Use the library of .Net Math functions

In addition to standard PowerShell methods we can also call .Net Math functions:

 .NET Math library:

  [math]::Round($var, p)  Round a variable to p places.
  [math]::Ceiling(n)   Rounds everything up, towards positive infinity.
  [math]::Equals(n,m)  Compare two values and return a [boolean] (true/false) result. (unlike -eq the types must also match)
  [math]::Exp(p)       Raise e to a power p
  [math]::Floor(n)     Rounds everything down, towards negative infinity.
  [math]::Log(n)    base e logarithm of n
  [math]::Log10(n)  base 10 logarithm of n
  [math]::Max(n,m)  Return the larger of two values
  [math]::Min(n,m)  Return the smaller of two values
  [math]::Pow(n,p)  Raise a number n to a power p
  [math]::Round(n,p) Round a number n to p decimal places. Default=0 decimal places.
  [math]::Sqrt(n)   Square Root of a number n
  [math]::Truncate(n)  Remove the decimal returning only an Integer. Rounds toward zero.

The trig functions all accept an angle, measured in radians.
To convert degrees to radians multiply by pi/180 using [Math]::PI 


Static mathematical constants:

You can list all the static memners of system.math like this: (via /\/\o\/\/ )

 [system.math] | gm -static


Find the Minimum value of two variables:

$var1 = 764.4
$var2 = 1409
$answer = [math]::min($var1,$var2)

Find the Tangent of 45 degrees:

$answer = [System.Math]::Tan(45/180*[System.Math]::PI)

“ Film is one of the three universal languages, the other two: mathematics and music” ~ Frank Capra

Related PowerShell Cmdlets

math.class - MSDN scroll down for full definitions.
Concatenation - Several methods to combine strings together.
PowerShell Operators - More advanced Operators for Arrays and formatting expressions.

Copyright © 1999-2023
Some rights reserved