Imports System
Public Class Test
Public Shared Sub Main()
Dim fd As New FactorDecimal(2)
Dim Input As String = "415276"
Console.WriteLine("Input: " & Input)
'Adding characters.'
For Each c As Char In Input
fd.AppendNumber(c)
Next
Console.WriteLine("Result: " & fd.ToString())
Console.WriteLine()
'Removing characters "152" from "415276".'
fd.RemoveRange(1, 3)
Console.WriteLine("RemoveRange(1, 3): " & fd.ToString())
End Sub
End Class
Public Class FactorDecimal
Private _value As String = "0"
Public DecimalPlaces As Integer
Public Sub AppendNumber(ByVal Character As Char)
If Char.IsNumber(Character) = False Then Throw New ArgumentException("Input must be a valid numerical character!", "Character")
_value = (_value & Character).TrimStart("0"c)
End Sub
Public Sub RemoveRange(ByVal Index As Integer, ByVal Length As Integer)
If _value.Length >= Me.DecimalPlaces + 1 AndAlso _
Index + Length > _value.Length - Me.DecimalPlaces Then Length -= 1 'Exclude decimal point.'
If Index + Length >= _value.Length Then Length = _value.Length - Index 'Out of range checking.'
_value = _value.Remove(Index, Length)
If _value.Length = 0 Then _value = "0"
End Sub
Public Overrides Function ToString() As String
Dim Result As Decimal
If Decimal.TryParse(_value, Result) = True Then
'Divide Result by (10 ^ DecimalPlaces) in order to get the amount of decimal places we want.'
'For example: 2 decimal places => Result / (10 ^ 2) = Result / 100 = x,xx.'
Return Result / (10 ^ Me.DecimalPlaces).ToString("0." & New String("0"c, Me.DecimalPlaces))
End If
Return "<parse error>"
End Function
Public Sub New(ByVal DecimalPlaces As Integer)
If DecimalPlaces <= 0 Then DecimalPlaces = 1
Me.DecimalPlaces = DecimalPlaces
End Sub
End Class