How to calculate % change from X to Y in VB.NET

1 Answer

0 votes
Imports System
Imports System.Math

Module PercentChangeProgram

    Function PercentChange(x As Double, y As Double) As Double
        Return ((y - x) / Abs(x)) * 100.0
    End Function

    Function DescribeChange(x As Double, y As Double) As String
        Dim pct As Double = PercentChange(x, y)

        If pct > 0 Then
            Return String.Format(
                "From {0:F1} to {1:F1} is a {2:F2}% increase (+{2:F2}%)",
                x, y, pct
            )
        ElseIf pct < 0 Then
            Return String.Format(
                "From {0:F1} to {1:F1} is a {2:F2}% decrease ({3:F2}%)",
                x, y, Abs(pct), pct
            )
        Else
            Return String.Format(
                "From {0:F1} to {1:F1} is no change",
                x, y
            )
        End If
    End Function

    Sub Main()
        Console.WriteLine(DescribeChange(-80.0, 120.0))
        Console.WriteLine(DescribeChange(120.0, 30.0))
    End Sub

End Module



' run:
'
' From -80.0 to 120.0 is a 250.00% increase (+250.00%)
' From 120.0 to 30.0 is a 75.00% decrease (-75.00%)
'

 



answered May 29 by avibootz
...