Reputation: 507
Im attempting to get this function to return a masked number. Say i have number 123456789. Im trying to get it to return *6789 if i give in an unmasked value of 4, or *789 if i give it an unmasked value of 3. Currently it is showing the number of digits in the number, which is what im trying to hide. I have been toying around with this but i cant quite get it to do what I want.
Public Function GetMaskedNumber(ByVal sNumber As String, ByVal iUnmaskedLength As Integer, ByVal sMaskChar As String) As String
sMaskChar = Trim(sMaskChar)
If iUnmaskedLength > 0 AndAlso Len(sMaskChar) > 0 Then
GetMaskedNumber = New String(sMaskChar(0), iUnmaskedLength)
If iUnmaskedLength < Len(sNumber) Then
Mid(GetMaskedNumber, (Len(sNumber) - iUnmaskedLength), iUnmaskedLength + 1) = Right(sNumber, iUnmaskedLength)
Else
GetMaskedNumber = sNumber
End If
Else
GetMaskedNumber = sNumber
End If
End Function
Upvotes: 0
Views: 2509
Reputation: 11773
With some error checking.
test code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'test
Dim i As Long = Long.MaxValue
Dim s As String = GetMaskedNumber(i, 12)
s = GetMaskedNumber(i, 20)
End Sub
the function
Public Function GetMaskedNumber(ByVal theNum As Long, _
ByVal UnmaskedLength As Integer, _
Optional MaskChar As String = "*") As String
Dim retval As String = theNum.ToString
If retval.Length > UnmaskedLength Then
retval = String.Format("{0}{1}", MaskChar, retval.Substring(retval.Length - UnmaskedLength))
Else
'ERROR???
Stop
End If
Return retval
End Function
Upvotes: 0
Reputation: 234715
If you have the number you want to mask as an Integer (say iNumber) rather than a string, you could use
"*" & CStr(iNumber mod (10 ^ iUnmaskedLength))
(Note that in vb.net ^
is exponentation.)
If you don't and need to work with sNumber then use
"*" & Right(sNumber, iUnmaskedLength)
Right()
allows iUnmaskedLength
to be larger than the length of the string; in such cases it returns the input string.
Upvotes: 3