A Million Little Pieces Of My Mind

NamtiraLib

SuperMath

By: Paul S Cilwa Posted: 4/10/2026 Page Views: 23
Hashtags: #Namtira #VisualBasic #VBNET #ClassLibrary #NamtiraLib #SuperMath #Percentage #Math
Math utilities including a Percentage class for managing clamped values.
Estimated reading time: 2 minute(s) (345 words)

SuperMath currently contains the Percentage class, which manages a value and its maximum, automatically clamping the value between zero and the maximum. You can read or write either the raw value or the percentage, and the class keeps everything in sync. Two shared helper functions provide quick calculations without creating an object.

Class Percentage
MemberParametersExample
NewaValue As Single, aMaxValue As SingleDim p As New Percentage(25, 200)
Valuep.Value = 50
MaxValuep.MaxValue = 100
Percentp.PercentSingle
CalcPercentage (Shared)aValue, aMaxValuePercentage.CalcPercentage(25, 200)12.5
CalcValue (Shared)aPercentage, aMaxValuePercentage.CalcValue(50, 200)100

Constructor and Properties

The constructor accepts a value and maximum, clamping the value to the valid range. The Value property clamps on set; the MaxValue property also adjusts the value downward if the new maximum is smaller. Percent exposes the value as a percentage (0–100) and recalculates the raw value when set.

Public Class Percentage Private MyValue As Single Private MyMaxValue As Single Public Sub New(aValue As Single, aMaxValue As Single) MyMaxValue = aMaxValue MyValue = Math.Min(Math.Max(0, aValue), MyMaxValue) End Sub Property Value As Single Set(aValue As Single) MyValue = Math.Min(Math.Max(0, aValue), MaxValue) End Set Get Return MyValue End Get End Property Property MaxValue As Single Set(aMax As Single) MyMaxValue = Math.Max(0, aMax) If MyMaxValue < MyValue Then MyValue = MyMaxValue End Set Get Return MyMaxValue End Get End Property Property Percent As Single Set(NewPercent As Single) NewPercent = Math.Min(Math.Max(0, NewPercent), 100) Value = MaxValue * NewPercent / 100 End Set Get Return Value / MaxValue * 100 End Get End Property

Shared Helper Functions

CalcPercentage returns the percentage of a value relative to a maximum. CalcValue returns the raw value corresponding to a given percentage, clamped to 0–100.

Public Shared Function CalcPercentage(aValue As Single, aMaxValue As Single) As Single Return aValue / aMaxValue * 100.0 End Function Public Shared Function CalcValue(aPercentage As Single, aMaxValue As Single) As Single aPercentage = Math.Min(Math.Max(0, aPercentage), 100) Return aMaxValue * aPercentage / 100.0 End Function End Class