Skip to content

Instantly share code, notes, and snippets.

@TheFreeman193
Last active May 9, 2021 16:51
Show Gist options
  • Save TheFreeman193/e714633119ed68a3ce1d6c8e06260291 to your computer and use it in GitHub Desktop.
Save TheFreeman193/e714633119ed68a3ce1d6c8e06260291 to your computer and use it in GitHub Desktop.
Get-PercentageDifference
# An advanced version of this script is now in my scripts collection:
# https://github.com/TheFreeman193/Scripts/blob/main/PowerShell/Tools/Get-RelativeDifference/Get-RelativeDifference.ps1
Function Get-PercentageDifference {
<#
.SYNOPSIS
Calculates percentage difference.
.DESCRIPTION
Calculates percentage difference between two values,
$A and $B, to the precision specified by $Precision.
.PARAMETER A
The first value to compare against
.PARAMETER B
The second value to compare against
.PARAMETER Precision
Level of precision (digits). Default = 2
.INPUTS
None. Get-PercentageDifference does not accept pipeline input.
.OUTPUTS
System.String. Get-PercentageDifference returns a string
representation of the percentage diffence.
.EXAMPLE
PS> Get-PercentageDifference -A 15 -B 30
66.67%
.EXAMPLE
PS> Get-PercentageDifference 15 30
66.67%
.EXAMPLE
PS> $First, $Second = -154, 12
PS> gpd $First $Second 5
233.80282%
#>
[CmdletBinding(ConfirmImpact = 'None')]
[Alias('Get-PercentDiff', 'gpd')]
param(
[Parameter(Mandatory, Position = 0)]
[Alias('X')]
[Int64]
$A,
[Parameter(Mandatory, Position = 1)]
[Alias('Y')]
[Int64]
$B,
[Parameter(Position = 2)]
[Alias('P')]
[UInt16]
$Precision = 2
)
# Format as a % to $Precision digits
"{0:P$Precision}" -f (
# Formula: 2 * |A - B| / |A + B|
2 * [math]::Abs($A - $B) /
[math]::Abs($A + $B)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment