Search code examples
vb.netmasking

Masking a number by showing last "x" digits with 1 mask character in front


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

Solution

  • 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.