Functions in script

Need to use two function in a single line. i.e. (Divide and multiplication should be in the same line of $result).

function Percentage([float]$a,[float]$b){
$result = divide $a $b
$result = multiply $result 100
return $result
}

Hello @maunilkshatriya,
You can use $() subexpression:

function Percentage([float]$a,[float]$b){

    return multiply $(divide $a $b) 100
}

Hope that helps.

1 Like

even without subexpressions too
multiply (divide $a $b) 100

2 Likes

Get-Percentage

  • Returns the percentage of one float to another.
    • Two result types for duel functionality (display, math).
    • Output is [string] formatted as Percent when -ShowSign is declared.
  • Adjust the scale (5) to control accuracy of result.
  • PS Version: 5.1.14409.1018

Tip: PowerShell 7.1 allows param attribute [ValidateRange("Positive")]. This could replace the need for a try\catch on the denominator value (not shown).

function Get-Percentage([float]$num,[float]$denom,[switch]$ShowSign)
{
    switch ($ShowSign)
    {
        $true {[decimal]::Round($num/$denom,5).ToString("p"); break}
        $false {100*([decimal]::Round($num/$denom,5))}
    }
}

# test
[float]$a = 50; [float]$b = 100;
[float]$i = 7.654; [float]$j = 35.343;
cls;
Get-Percentage $a $b -ShowSign;
Get-Percentage $i $j -ShowSign;
Get-Percentage $i $j;

# results
50.00 %
21.66 %
21.65600
1 Like